pthread_create分段错误

Zac*_*ach 5 c++ pthreads segmentation-fault

我正在我的程序中使用'pthread_create'方法,并在此方法中获得分段错误.
什么可能导致这种情况?我正在使用正确的参数类型调用此函数!

这是代码:

pthread_t* _daemon;


void* writer(void* arg){
    // stuff that dont involve "arg"...
}


int initdevice(){
    if(pthread_create(_daemon, NULL, &writer, NULL) != 0) //seg in this line
    {

      cerr << "system error\n";
      return ERR_CODE;
    }
    return SUCCESS;
}

int main () {
    initdevice();
    return 0;
}  
Run Code Online (Sandbox Code Playgroud)

注意:我在pthread_create中调用writer之前尝试运行它也没有'&',而且 - 我们尝试向此方法发送一些void*参数而不是最后一个NULL参数.

Mar*_*ork 17

你的探测器在这里:

pthread_t* _daemon;
Run Code Online (Sandbox Code Playgroud)

这应该是:

pthread_t  daemon;
Run Code Online (Sandbox Code Playgroud)

然后将调用更改为pthread_create:

if(pthread_create(&daemon, NULL, &writer, NULL) != 0)
Run Code Online (Sandbox Code Playgroud)

这个想法是pthread_create接受一个指向现有 pthread_t对象的指针,以便它可以填充细节.您可以将其视为构造函数的C版本.最初,pthread_t对象未初始化,因此初始化它.

此外,您的代码仍然可能无法始终工作,因为您不等待线程完成.确保你的主线程没有在所有孩子面前完成:

int main () 
{
    initdevice();
    pthread_join(daemon, NULL); // wait for the thread to exit first.
    return 0;
}  
Run Code Online (Sandbox Code Playgroud)

  • @Nissim:因为你的方式错了!您正在将一个初始化指针(因此它可以指向任何东西)传递给通过指针写入的函数(从而在内存中的任何位置写入). (2认同)