pthread_kill 与pthread_cancel使用方法

pthread_kill 与pthread_cancel使用方法

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* thread0(void* arg)
{
    pthread_mutex_lock(&mutex);
    printf("in thread 0 tag 1\n");
    pthread_cond_wait(&cond, &mutex);
    printf("in thread 0 tag 2\n");
    pthread_mutex_unlock(&mutex);
    printf("in thread 0 tag 3\n");
    pthread_exit(NULL);
}

void* thread1(void* arg)
{
    sleep(10);
    printf("in thread 1 tag 1\n");
    pthread_mutex_lock(&mutex);
    printf("in thread 1 tag 2\n");
    pthread_cond_broadcast(&cond);
    pthread_mutex_unlock(&mutex);
    printf("in thread 1 tag 3\n");
    pthread_exit(NULL);
}
int main()
{
    pthread_t tid[2];
    if (pthread_create(&tid[0], NULL, thread0, NULL) != 0) 
    {
        exit(1);
    }
    if (pthread_create(&tid[1], NULL, thread1, NULL) != 0) 
    {
        exit(1);
    }
    sleep(5);
    printf("in main thread tag 1\n");
    pthread_cancel(tid[0]);
    //pthread_kill(tid[0],3);
    pthread_join(tid[0], NULL);
    printf("tid0\n");
    pthread_join(tid[1], NULL);
    printf("tid1\n");
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;
}

使用pthread_cancel 结果如下:
in thread 0 tag 1
in main thread tag 1
tid0
in thread 1 tag 1

pthread_cancel kill 掉线程,但是如果有类似拿锁的操作,则要等拿到锁才能kill掉。


pthread_kill 结果如下:

in thread 0 tag 1
in main thread tag 1
Quit

pthread_kill 会对线程0发出signal_quit(3)的系统信号。 如果线程0不处理,则整个进程退出。




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值