C ++多线程 [英] c++ multithread

查看:70
本文介绍了C ++多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C ++实现线程类.我的代码如下所示. 我有一个关于如何访问线程数据的问题. 在Thread类中,我使用pthread_create()函数创建了一个线程.然后调用EntryPoint()函数启动创建的线程.在运行功能中,我要访问mask变量,它始终显示段故障. 所以,我的问题是新创建的线程是否复制原始类中的数据?如何访问线程自己的数据?

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

推荐答案

我不熟悉您使用的库,但是EntryPoint如何知道pthis是指向Thread的指针?线程(this)似乎没有传递给pthread_create.

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.

这篇关于C ++多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆