Using a class function in int main()

前端 未结 6 949
悲哀的现实
悲哀的现实 2020-12-20 09:49

I am having problems calling my functions from my main program.
These functions HAVE to be in my class.
How do I access them from my int main()?

#inc         


        
相关标签:
6条回答
  • 2020-12-20 10:09

    You are calling class methods as just waitSemaphore without creating the object of myCountingSemaphoreUsingBinarySemaphore.

    You should create the object first.

    myCountingSemaphoreUsingBinarySemaphore obj;
    obj.waitSemaphore(mutex1);
    
    0 讨论(0)
  • 2020-12-20 10:17

    The two threads you create (via reader_writer()) do nothing. main() just goes into the first do loop with no way of getting out.

    Also, you seem to have confused mutex, semaphores, and condition variables. The function names makes it look like you're trying to implement condition variables in your class. But you're building it as just wrappers to mutex locks.

    And finally, you are calling pthread_mutex_lock() et al. on a pthread_t when those functions are supposed to be called on a pthread_mutex_t.

    There probably are other errors, but these are the ones that really jump out. Basically, you need to review multi-threaded programming, both in terms of how threads are created, and how they are synchronized.

    0 讨论(0)
  • 2020-12-20 10:21

    Functions inside a class are called methods. You need to instantiate an object of that class to be able to use it's methods:

    myCountingSemaphoreUsingBinarySemaphore obj; // obj is an instance of the class
    
    obj.waitSemaphore(&mutex1);
    
    obj.signalSemaphore(&mutex1);
    

    EDIT:

    By the way, pthread_create and pthread_join take a pthread_t* and not a mutex!

    int pthread_create(pthread_t* thread, 
                       pthread_attr_t* attr, 
                       void* (*start_routine)(void*), 
                       void* arg);
    
    0 讨论(0)
  • 2020-12-20 10:24

    karlphillip was right, you need to pass by pointer instead of reference

    BTW, following line are mistake also, the pthread_create accept and pthread_t instead of pthread_mutex_t

    pthread_create( &mutex1, NULL, reader_writer, void);

    pthread_create( &wrt, NULL, reader_writer, void);

    0 讨论(0)
  • 2020-12-20 10:25

    You can either declare those methods as static or use an object to make the calls:

    myCountingSemaphoreUsingBinarySemaphore s;
    s.waitSemaphore(wrt);
    
    0 讨论(0)
  • 2020-12-20 10:27

    You need to create an instance of the class (an object) in order to call his member functions.

    In this particular code the member functions has no reason to be instance and could be static:

    class foo{
        public:
    
        static void bar(int val)
        {
        //do something
        }
        };
    
    int main()
    {
       foo::bar(10);
    }
    
    0 讨论(0)
提交回复
热议问题