Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();  
}
like image 725
chnet Avatar asked Dec 21 '25 07:12

chnet


1 Answers

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.

like image 54
500 - Internal Server Error Avatar answered Dec 23 '25 19:12

500 - Internal Server Error



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!