Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread function from a class

Tags:

c++

pthreads

Let's say I have a class such as

class c {      // ...     void *print(void *){ cout << "Hello"; } } 

And then I have a vector of c

vector<c> classes; pthread_t t1; classes.push_back(c()); classes.push_back(c()); 

Now, I want to create a thread on c.print();

And the following is giving me the problem below: pthread_create(&t1, NULL, &c[0].print, NULL);

Error Ouput: cannot convert ‘void* (tree_item::)(void)’ to ‘void* ()(void)’ for argument ‘3’ to ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)’

like image 354
Angel.King.47 Avatar asked Jul 20 '09 03:07

Angel.King.47


People also ask

What is the use of pthread_join () and pthread_exit () function?

On return from a successful pthread_join() call with a non-NULL value_ptr argument, the value passed to pthread_exit() by the terminating thread shall be made available in the location referenced by value_ptr. When a pthread_join() returns successfully, the target thread has been terminated.

What does pthread_create function return?

pthread_create() returns zero when the call completes successfully. Any other return value indicates that an error occurred.

Can we use pthread in C++?

In a Unix/Linux operating system, the C/C++ languages provide the POSIX thread(pthread) standard API(Application program Interface) for all thread related functions. It allows us to create multiple threads for concurrent process flow.

How do I pass multiple arguments to pthread?

For cases where multiple arguments must be passed, this limitation is easily overcome by creating a structure which contains all of the arguments, and then passing a pointer to that structure in the pthread_create() routine. All arguments must be passed by reference and cast to (void *).


1 Answers

You can't do it the way you've written it because C++ class member functions have a hidden this parameter passed in. pthread_create() has no idea what value of this to use, so if you try to get around the compiler by casting the method to a function pointer of the appropriate type, you'll get a segmetnation fault. You have to use a static class method (which has no this parameter), or a plain ordinary function to bootstrap the class:

class C { public:     void *hello(void)     {         std::cout << "Hello, world!" << std::endl;         return 0;     }      static void *hello_helper(void *context)     {         return ((C *)context)->hello();     } }; ... C c; pthread_t t; pthread_create(&t, NULL, &C::hello_helper, &c); 
like image 89
Adam Rosenfield Avatar answered Sep 27 '22 18:09

Adam Rosenfield