2011-08-07 142 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甚至不安全。如果線程按照您所說的那樣終止,該怎麼辦?