日期:2014-05-16  浏览次数:22452 次

线程 Segmentation fault (core dumped)
小弟初学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

请高手指点

------解决方案--------------------
因为你的主线程比你的子线程先结束了,你加sleep后,主线程就在子线程之后结束了。
------解决方案--------------------
可以使用函数pthread_join,让主线程等一下子线程
------解决方案--------------------
getpid()得到的是进程id,所以是一样的

------解决方案--------------------
printf不是线程安全的函数哦, 因为它们都操作FILE *stdin, 所以你最好让主线程pthread_join返回后再输出父进程的信息.
------解决方案--------------------
pid是进程id,你是要获取线程标识用pthread_self()
------解决方案--------------------
探讨
可以使用函数pthread_join,让主线程等一下子线程