2011-08-07 33 views
3

我正在使用不分配任何本地变量的pthread。由于我不想进入这里,我需要一个pthread_cancel()选项,我写的线程应该能够支持它(没有资源清理,可以随时停止执行)。目前,我遇到问题,因为pthread_cancel在pthread实际运行完成之前返回,导致只有在取消线程后我才会触摸的共享资源出现问题。等待pthread_cancel结束

有什么办法可以知道我的pthread何时完好无损?有没有可能是我没有找到的函数,或者我不熟悉的参数?

pthread_cancel(thread_handle); 
pthread_join(thread_handle, NULL); 

做的伎俩,或者说不能保证(因为thread_handle可能已经是无效的)?

我对pthreads很新,所以最好的做法是欢迎(除了“不要使用pthread_cancel()”,我已经了解到:P)。

回答

3

kernel.org手册页实际上是在做它。它是安全的。

s = pthread_cancel(thr); 
if (s != 0) 
    handle_error_en(s, "pthread_cancel"); 

/* Join with thread to see what its exit status was */ 

s = pthread_join(thr, &res); 
if (s != 0) 
    handle_error_en(s, "pthread_join"); 
1

直到你在可连接的线程上调用pthread_join,它的tid仍然有效。如果线程可以连接(它必须为pthread_cancel保证安全),那么thread_handle必须仍然有效。

如果线程已分离,则拨打pthread_cancel甚至不安全。如果线程按照您所说的那样终止,该怎么办?