views:

105

answers:

4
+2  Q: 

c++ multithread

I use C++ to implement a thread class. My code shows in the following. I have a problem about how to access thread data. In the class Thread, I create a thread use pthread_create() function. then it calls EntryPoint() function to start thread created. In the Run function, I want to access the mask variable, it always shows segment fault. So, my question is whether the new created thread copy the data in original class? How to access the thread own data?

class Thread {
public:
  int mask;
  pthread_t thread;

  Thread( int );
  void start();
  static void * EntryPoint (void *);
  void Run();
};

Thread::Thread( int a) {
  mask =a; 
}

void Thread::Run() {

  cout<<"thread begin to run" <<endl;
  cout << mask <<endl;       // it always show segmentfault here
}

void * Thread::EntryPoint(void * pthis) {
  cout << "entry" <<endl;
  Thread *pt = (Thread *) pthis;
  pt->Run();
}

void Thread::start() {

  pthread_create(&thread, NULL, EntryPoint, (void *)ThreadId );
  pthread_join(thread, NULL);
}

int main() {
  int input_array[8]={3,1,2,5,6,8,7,4};
  Thread t1(1);
  t1.start();  
}
+2  A: 

I'm not familiar with the libraries you're using, but how does EntryPoint know that pthis is a pointer to Thread? Thread (this) does not appear to be passed to pthread_create.

500 - Internal Server Error
You are right. I should pass this to pthread_create(). Thanks.
chnet
Watch out for the object lifetime, as well. See my post below or else you're still going to have issues. ;)
Nathan Ernst
+1  A: 

It's great that you're attempting to write a Thread class for educational purposes. However, if you're not, why reinvent the wheel?

wheaties
Yeah, for education purpose. Could you pls give me some hints about the already "wheel"? I am a novice to multitheading.
chnet
Boost provides a great platform independent thread implementation that I've linked. If you're trying to learn multi-threading then I suggest using Boost. It'll spare you from having to get down to the nitty-gritty while learning C++ multi-threading issues.
wheaties
A: 

pThis is most likely NULL, you should double check that you're passing the correct arguments to pthread_create.

Dan Olson
+1  A: 

Basically, the problem is as soon as you start your thread, main exits and your local Thread instance goes out of scope. So, because the lifetime of your thread object is controlled by another thread, you've already introduced a race condition.

Also, I'd consider joining a thread immediately after you've created it in Thread::start to be a little odd.

Nathan Ernst