线程取消

int pthread_cancel(pthread_t th);

该函数运行一个线程取消指定的另一个线程th

函数成功,返回0,否则,返回非0;

/***
cancel.c
***/
#include<stdio.h>
#include<pthread.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>

void * func(void *arg)
{
    while(1)
    {
        printf("fun run...\n");
        sleep(1);
    }
    return NULL;
}

int main()
{
    pthread_t t1;
    int err = pthread_create(&t1,NULL,func,NULL);
    if( 0 != err)
    {
        printf("thread_create failled : %s\n",strerror(errno));
    }
    else
    {
        printf("thread_create success\n");
    }
    sleep(5);
    pthread_cancel(t1);
    pthread_join(t1,NULL);
    return EXIT_SUCCESS;
}

函数运行结果:

exbot@ubuntu:~/wangqinghe/thread/20190729$ ./cancel

thread_create success

fun run...

fun run...

fun run...

fun run...

fun run...

猜你喜欢

转载自www.cnblogs.com/wanghao-boke/p/11264648.html