判断线程是否已经结束

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89071529

一 代码

#include <iostream>  
#include <pthread.h>  
#include <signal.h>  
#include <unistd.h> //sleep
#include "errno.h"
using namespace std;

void *thfunc(void *arg)   // 线程函数
{
    int tm = 50;
    while (1)
    {
        cout << "thrfunc--left:"<<tm<<" s--" <<endl;
        sleep(1);
        tm--;
    }
    return (void *)0;   
}

int main(int argc, char *argv[])
{
    pthread_t     pid;  
    int res;
    
    res = pthread_create(&pid, NULL, thfunc, NULL);   // 创建线程
    sleep(5);
    int kill_rc = pthread_kill(pid, 0);   // 发送信号0,探测线程是否存活

    // 打印探测结果
    if (kill_rc == ESRCH)
        cout<<"the specified thread did not exists or already quit\n";
    else if (kill_rc == EINVAL)
        cout<<"signal is invalid\n";
    else
        cout<<"the specified thread is alive\n";
     
    return 0;
}

二 运行

[root@localhost test]# g++ -o test test.cpp -lpthread
[root@localhost test]# ./test
thrfunc--left:50 s--
thrfunc--left:49 s--
thrfunc--left:48 s--
thrfunc--left:47 s--
thrfunc--left:46 s--
the specified thread is alive

三 说明

上面例子中主线程休眠5秒,探测了线程是否存活,结果是活着。

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/89071529
今日推荐