您的位置:首页 > 其它

调用系统函数pthread_cancel取消进程的其他线程

2011-10-10 23:04 621 查看
调用系统函数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;
}


运行结果如下图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: