So, I am using C++11 and I made a class
Class C
{
private:
queue<std::int> s;
pthread_t x;
public:
C() {phthread_create(&x, NULL, d_q, NULL);
void log(int p); // pushes into q.
void* d_q(void* q); // this is a function which will pop s. assume s is thread safe.
}
The problem is the line pthread_create(&x, NULL, d_q, NULL)
. It gives me Error: Reference to non-static member must be called.
I get rid of this problem by making pthread_t x static
. But I dont want to do this because of 2 reasons:
- Creation of a thread with a static function means only 1 copy of the function.
- The thread is created in a constructor. I don't know what will happen if I create more than one objects of class C.
Can someone please give me a workaround?
Solved: Thanks for the help! Also, a very good advice is to prefer std::thread over pthread for future users!
As for your problem, you a pointer to a (non-static) member function is not the same as a pointer to a member function. Non-static member functions needs an instance of an object to be called on.
There are a couple of ways to solve this: If you insist on using POSIX thread functions then you could make a
static
wrapper function, pass the instance as an argument to the thread, and in the static wrapper function call the actual function using the object passed.Another solution is to use
std::thread
, which will make it much easier: