調用系統函數pthread_cancel取消進程的其他線程

調用系統函數pthread_cancel取消進程的其他線程
        先在主線程中創建一子線程,在子線程中一直輸出運行了多少時間,在主進程監控,當發現子線程已經運行10秒的時候,取消子線程。
Demo代碼如下:
注意編譯的時候要加 -lpthread 選項,即unix的線程庫。
#include <iostream>
#include <pthread.h>
using namespace std;

void * thread_fun(void * arg) 
{
	cout << "child thread ID : " << pthread_self() << endl;
	int cnt = 0;
	while (true) 
	{
		sleep(1);
		cout << "child thread run " << ++cnt << "second" << endl;
	}
}

int main()
{
	int err;	
	pthread_t tid1;
	
	err = pthread_create(&tid1, NULL, thread_fun, NULL);
	if (err != 0) 
	{
		cout << "can't create thread" << endl;
	}
	
	int cnt = 0;
	while (true) 
	{
		sleep(1);
		cnt++;
		if (cnt == 10) 
		{
			cout << "main thread cancel the child thread."<< endl;
			cout << "main thread ID : " << pthread_self() << endl;
			cout << "child thread ID : " << tid1 << endl;
			pthread_cancel(tid1);
			break;
		}
	}
	return 0;
}

運行結果如下圖:


發佈了270 篇原創文章 · 獲贊 12 · 訪問量 52萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章