chnet
chnet

Reputation: 2033

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();  
}

Upvotes: 3

Views: 1760

Answers (4)

Nathan Ernst
Nathan Ernst

Reputation: 4590

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.

Upvotes: 0

Dan Olson
Dan Olson

Reputation: 23387

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

Upvotes: 0

wheaties
wheaties

Reputation: 35990

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

Upvotes: 1

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.

Upvotes: 2

Related Questions