pthread_kill的用法

本文介绍了一个使用C语言实现的多线程程序示例,其中包括如何创建线程、处理信号、阻塞信号等关键操作。通过两个不同的线程,演示了在接收到信号时线程的不同行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
void sighand(int signo){
fprintf(stdout, "Thread %u in signal handler\n", (unsigned int )pthread_self());
}


void* func(void* param){
unsigned int uid = (unsigned int)pthread_self();
printf("enter thread %u\n", uid);
int rc = sleep(30); 
if(rc != 0){
fprintf(stderr, "thread %u fail\n", uid);
return NULL;
}
fprintf(stdout, "thread %u success\n", uid);
return NULL;
}


void* maskedFunc(void* param){
unsigned int uid = (unsigned int)pthread_self();
printf("enter masked thread %u\n", uid);
sigset_t mask; 
int rc; 
sigfillset(&mask);
rc = pthread_sigmask(SIG_BLOCK, &mask, NULL);
if(rc != 0){
fprintf(stderr, "error occured in thread %u", uid);
return NULL;
}
rc = sleep(30);
if(rc != 0){
fprintf(stderr, "masked thread %u fail\n", uid);
return NULL;
}
fprintf(stdout, "masked thread %u success\n", uid);
return NULL;
}






int main(int argc, char **argv){
struct sigaction actions; 
memset(&actions, 0, sizeof(actions));
sigemptyset(&actions.sa_mask);
actions.sa_flags = 0; 
actions.sa_handler = sighand;
sigaction(SIGALRM, &actions, NULL);
int rc; 
pthread_t pid1, pid2; 
rc = pthread_create(&pid1, NULL, func, NULL);
if(rc != 0){
fprintf(stderr, "error:%s\n", strerror(rc));
}
rc = pthread_create(&pid2, NULL, maskedFunc, NULL);
if(rc != 0){
fprintf(stderr, "error:%s\n", strerror(rc));
}
sleep(3);
//send msg
pthread_kill(pid1, SIGALRM);
pthread_kill(pid2, SIGALRM);


//wait for threads to complete 
pthread_join(pid1, NULL);
pthread_join(pid2, NULL);

fprintf(stdout, "main thread complete\n");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值