linux重复调用创建线程,pthread_create新建线程,为什么新线程执行的函数有时候会被调用两次?...

在看apue的第11章,按照书上的代码打了如下:

#include

#include

#include

#include

pthread_t ntid;

void printids(const char *s){

pid_t pid;

pthread_t tid;

pid = getpid();

tid = pthread_self();

printf("%s:pid %lu tid %lu (0x%lx)\n", s, (unsigned long) pid, (unsigned long) tid, (unsigned long)tid);

}

void *thr_fn(void *arg){

printids("new thread:");

return ((void *)0);

}

int main(){

int err;

err = pthread_create(&ntid, NULL, thr_fn, NULL);

printids("main thread:");

exit(0);

}

有时候只输出

main thread::pid 22506 tid 139699542841088 (0x7f0e55a05700)

这个我能理解,在主线程结束的时候,新线程还没来的及执行,就终止了。

多数情况是这样的

new thread::pid 22680 tid 140091717809920 (0x7f69a5137700)

main thread::pid 22680 tid 140091726059264 (0x7f69a5915700)

这个也是正常,但是有时候会出现

main thread::pid 22698 tid 140224862336768 (0x7f88a51bb700)

new thread::pid 22698 tid 140224854087424 (0x7f88a49dd700)

new thread::pid 22698 tid 140224854087424 (0x7f88a49dd700)

这是为什么?是什么导致新线程调了printids两次?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值