- 论坛徽章:
- 0
|
本帖最后由 crazyhadoop 于 2012-02-16 18:29 编辑
小弟初学linux, 根据书上写了个小程序
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void printids(const char *);
void *start(void *);
pthread_t ntid;
void printids(const char *s)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s : pid is %u, tid is %u (0x%x)\n", s, pid, tid, tid);
}
void *start(void *p)
{
printids("new thread");
return ((void *)0);
}
void main()
{
int err;
err = pthread_create(&ntid, NULL, start(NULL), NULL);
if(err != 0)
{
printf("error, cann't create new thread");
exit(0);
}
printids("main thread");
printf("start sleep\n");
sleep(5);
printf("end \n");
exit(0);
}
编译后执行,结果如下
[root@localhost test]# gcc thread.c -o thread -lpthread
[root@localhost test]# ./thread
new thread : pid is 2442, tid is 4008711936 (0xeef01700)
main thread : pid is 2442, tid is 4008711936 (0xeef01700)
start sleep
Segmentation fault (core dumped)
当我把程序中 sleep(5) 注释掉后编译执行正常,结果为
[root@localhost test]# gcc thread.c -o thread -lpthread
[root@localhost test]# ./thread
new thread : pid is 2830, tid is 2600584960 (0x9b01c700)
main thread : pid is 2830, tid is 2600584960 (0x9b01c700)
start sleep
end
而且main thread的线程id,和新创建线程new thread 的线程id 相同, 我不明白程序哪里出错了
我的系统是centos6.2,gcc version 4.4.6
请高手指点 |
|