pthread_kill导致程序崩溃 Segmentation fault

本文探讨了pthread_t类型的本质及其在Linux NPTL实现中的内部表示,并详细介绍了如何安全地使用pthread_t来管理线程生命周期,避免因错误操作导致程序崩溃。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pthread_t thread_id;

printf("thread = %d\n",pthread_kill(thread_id,0));

上述用法,在未对一个pthread_t执行pthread_create前调用pthread_kill,会出现Segmentation fault

google上摘录如下解释:

pthread_t is not a thread ID, or a numeric index. It is an opaque type. Making up values can result in a crash.

On Linux NPTL, pthread_t is used as a pointer:

int
__pthread_kill (threadid, signo)
     pthread_t threadid;
     int signo;
{
  struct pthread *pd = (struct pthread *) threadid;

It should be fairly clear where things are going wrong already :) Note that this pointerness is also an implementation detail - the older Linuxthreads implementation used numeric indices into a table, and there you could indeed make up TIDs and not expect things to crash.

You need to be tracking thread life and death yourself. A pthread_t is valid until you call pthread_join on it successfully. If you want to test whether a valid pthread_t is alive, call pthread_tryjoin_np on it; if it returns EBUSY, the thread is alive. If the function succeeds, the pthread_t is no longer valid; you must not re-use it at this point - so you must make a note somewhere that that thread is dead now, and there's no need to check it anymore!

You could, of course, implement your own tracking system - create a table somewhere of liveness, a system for handing out TIDs, and passing them into newly created threads. Have each thread mark itself as dead prior to exiting (perhaps using pthread_cleanup_push so you handle thread cancellation and pthread_exit), and detach the thread so you don't need to join it (using pthread_detach). Now you have explicit control of your thread-death reporting.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值