#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;
}
運行結果如下圖: