user5448913
user5448913

Reputation:

Encapsulating Threads creates problems

I have the following encapsulation for my pthread_t threads:

#include <pthread.h>

class Thread
{
public:
  void         run(const int);
  static void  *run_helper(void *);
  bool         startThread(int);
  void         joinThread();

  pthread_t     th;      
};

Where run is my thread routine, and run_helper is the following:

void     *Thread::run_helper(int num)
{
  return (Thread *)this->run(num);
}

I start my threads like such:

bool    Thread::startThread(intptr_t arg)
{
  return (pthread_create(&this->th, NULL, &run_helper(arg), (void *)(intptr_t)arg));
}

But when I compile, I get the following errors:

error: lvalue required as unary ‘&’ operand return (pthread_create(&this->th, NULL, &run_helper(arg), (void *)(intptr_t)arg));

error: ‘this’ is unavailable for static member functions return (Thread *)this->run(num);

And despite trying, I can't seem to make this encapsulation work.

Upvotes: 0

Views: 113

Answers (2)

mausik
mausik

Reputation: 77

For the first error, you need to cast the third argument into (void*(*)(void*)) and remove & (maybe the casting isn't neccessary).

pthread_create(&this->th, NULL, (void*(*)(void*))run_helper(arg), (void *)(intptr_t)arg);

The second error, you are trying to use pointer to this in a static function, but the function isn't called on any object, therefore you can't use this in a function like that. The solution is to cast arg into Thread* and then call the non-static run function.

Upvotes: 0

fetherolfjd
fetherolfjd

Reputation: 266

I think your issue might specifically be &this->th. & has higher precedence than ->. Perhaps try &(this->th).

Upvotes: 1

Related Questions