pthread_kill的用法

来源:互联网 发布:焉足以知是且非邪 编辑:程序博客网 时间:2024/06/06 11:46
#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");
}
原创粉丝点击