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

来源:互联网 发布:sql group by rollup 编辑:程序博客网 时间:2024/06/05 23:03
调用系统函数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;}

运行结果如下图:


原创粉丝点击