今天在使用pthread_create创建线程时,一运行,程序就立刻死掉,很是郁闷。
对比了一下我之前使用正常的pthread_create创建线程代码,

原来是这次我使用pthread_create创建线程时,第一个参数传进NULL,导致了程序死掉。

在Qt中的错误信息如下:

The program has unexpectedly finished.

在控制台中的错误信息如下:

Segmentation fault

---------------------------------------------------------------------------------------------------------

关于pthread_create的说明,可以man pthread_create看一下,我暂时先不看了。。。
有问题的代码如下:
pthread_create(NULL, NULL, ThreadTest, NULL); // 注意第一个参数传NULL会导致程序崩溃

gcc编译该例子的命令: gcc -lstdc++ -lpthread main.cpp
我测试程序崩溃的代码如下:

#include<stdio.h>
#include<pthread.h>

void *ThreadTest(void *arg)
{
printf("Enter ThreadTest \r\n");
}

int main(void)
{
pthread_t tid; // 这个不能省
if(pthread_create(NULL, NULL, ThreadTest, NULL) != 0) // 第一个参数不能传NULL,不然程序会崩溃
{
printf("Create thread error! \n");
}
else
{
printf("Create thread sucess! \n");
}

getchar();
return 0;
}



我测试程序正常的代码如下:



#include<stdio.h>
#include<pthread.h>

void *ThreadTest(void *arg)
{
printf("Enter ThreadTest \r\n");
}

int main(void)
{
pthread_t tid; // 这个不能省
if(pthread_create(&tid, NULL, ThreadTest, NULL) != 0) // 第一个参数不能传NULL,不然程序会崩溃
{
printf("Create thread error! \n");
}
else
{
printf("Create thread sucess! \n");
}

getchar();
return 0;
}