0

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:

  1. Creation of a thread with a static function means only 1 copy of the function.
  2. 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!

V Shreyas
  • 449
  • 5
  • 19
  • 3
    Try using `std::thread` instead. – Jonathan Potter Jun 19 '15 at 05:50
  • `std::int`? What's that? – Some programmer dude Jun 19 '15 at 05:51
  • Use `std::thread`. There are plenty examples on how to bind a non-static member function one of those. – juanchopanza Jun 19 '15 at 05:55
  • 2
    I'll note that creating a thread in a constructor is generally a bad idea - if you throw an exception in the ctor, you'll automatically destroy the object, but the thread is still running and trying to use the object. If the object is created in automatic scope (e.g. a local variable) you'll also run into destruction before the thread terminates unless you're careful to join it in the destructor. It's better to be explicit with a `start()` function or similar, in most cases. – bdonlan Jun 19 '15 at 07:33

1 Answers1

2

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:

class C
{
    std::thread thread_;
    ...
public:
    C() : thread_(&C::d_q, this) {}
    ...
    void d_q() { ... }
};
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621