2011-04-03 92 views
2

我在我的程序中使用了方法'pthread_create',并在此方法中出现了分段错误。
什么可能导致这种情况?我用正确的参数类型调用这个函数!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; 
} 

注:我试图调用到作家在pthread_create之前也运行它没有“&”,也是 - 我们尝试发送给该方法一些void *参数而不是最后一个NULL参数。

+4

发布你在这个调用中使用的代码,你可能做得不对。 – Mat 2011-04-03 16:53:45

+0

我认为问题出在第17行。 – Nawaz 2011-04-03 16:55:09

+1

不要使用下划线'_'作为全局变量的第一个字符(只是不要在变量的开头使用它们)。 [这些标识符保留给编译器和操作系统](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-ac-identifier/228797#228797 )。 – 2011-04-03 17:22:47

回答

13

你probelem是在这里:

pthread_t* _daemon; 

这应该是:

pthread_t daemon; 

然后改变调用在pthread_create:

if(pthread_create(&daemon, NULL, &writer, NULL) != 0) 

的想法是,在pthread_create需要一个指针一个现有的 pthread_t对象,以便它可以fil l在细节上。你可以把它看作构造函数的C版本。最初pthread_t对象是未初始化的,因此初始化它。

此外,您的代码仍然可能不会始终工作,因为您不等待线程完成。确保你的主线程不会所有的孩子之前完成:

int main() 
{ 
    initdevice(); 
    pthread_join(daemon, NULL); // wait for the thread to exit first. 
    return 0; 
} 
+0

非常感谢!为什么这种差异导致如此大的混乱? – Zach 2011-04-03 17:18:29

+1

@Nissim:因为你的方式错了!你传递一个初始化的指针(所以它可以指向任何东西)到一个通过指针写入的函数(从而写入内存中的任何地方)。 – 2011-04-03 17:20:43

1

必须分配_daemonvariablenewmalloc功能,因为你必须使用pointer的。像下面这样:

pthread_t* _daemon; 
_daemon = new pthread_t;