簡體   English   中英

在C中終止一個線程

[英]terminating a thread in C

我有一個調用線程的C程序。

iret1 = pthread_create( &thread1, NULL, readdata, NULL);
iret2 = pthread_create( &thread2, NULL, timer_func, NULL);
pthread_join(thread2, NULL);

線程2在執行某些功能后返回,之后我想停止執行線程1.我應該怎么做?

您可以使用pthread_cancel停止線程:

pthread_cancel(thread1);

readdata

/* call this when you are not ready to cancel the thread */
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
...
/* call this when you are ready to cancel the thread */
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

有關更多信息,請參見pthread_cancel手冊頁 - 其中包含一個示例。

如果您不想使用pthread_cancel,則可以使用由主線程設置並由線程1讀取的全局標志。此外,您可以使用任何IPC方法,例如在線程之間建立管道

您應該向線程發出信號,表示您希望它停止工作,然后等待它。 例如,您可以設置線程定期測試的布爾標志。 如果該標志指示已取消工作,則線程應從線程函數返回。

不要嘗試從外部強制終止線程,因為這會使同步對象處於不確定狀態,導致死鎖等。

Thread1必須有一個標志,它會不時地驗證它是否應該自行中止。

有一些方法可以從外部中止一個線程,但這非常危險。 別。

就像是:

thread1stop=TRUE; //Thread 1 has access to this boolean value
pthread_join(thread1, NULL);

您可以通過調用pthread_cancel(thread1)來停止thread1。

tkill(tid,SIGTERM)是您正在尋找的電話我相信。

pthread_cancel()函數向線程發送取消請求。

在發送取消線程的請求后,您應該檢查返回代碼以確認線程是否實際被取消。

這是一個簡單的例子:

rc = pthread_cancel(iret2);
if(rc) printf("failed to cancel the thread\n");

供進一步參考:

http://cursuri.cs.pub.ro/~apc/2003/resources/pthreads/uguide/users-39.htm

其他可能對您有用的來源。

http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_create.3.html

http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_cancel.3.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM