Posted on 2009-08-05 14:25
Prayer 阅读(421)
评论(0) 编辑 收藏 引用 所属分类:
LINUX/UNIX/AIX
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define THREAD_NUM 3
pthread_t threadBuf[THREAD_NUM];
int tcBuf[THREAD_NUM];
void* threadOpr1(void* arg);
void* threadOpr2(void* arg);
/**********************************
试验一个线程杀死其他的线程
但是进程不退出
***********************************/
int main(){
int i=0;
for(i = 0; i < THREAD_NUM; i++){
tcBuf[i] = i + 1;
if( (pthread_create(&threadBuf[i], NULL,threadOpr1,
&tcBuf[i])) != 0 ) {
printf("pthread_create \n");
return -1;
}
}
sleep(5);
if( (pthread_create(&threadBuf[i], NULL,threadOpr2,
NULL)) != 0 ) {
printf("pthread_create \n");
return -1;
}
sleep(30);
printf("main exit\n");
return 0;
}
/**********************************
被杀死的线程函数
***********************************/
void* threadOpr1(void* arg){
int tcId=*(int *)arg;
int i=0;
while(i<10){
printf("%d live\n",tcId);
i++;
sleep(2);
}
printf("killed exit\n");
pthread_exit(NULL);
}
/**********************************
杀死其他线程的线程
***********************************/
void* threadOpr2(void* arg){
int i=0;
for(i = 0; i < THREAD_NUM; i++){
if( (pthread_kill(threadBuf[i],SIGTERM)) != 0 ) {
printf("pthread_kill \n");
pthread_exit(NULL);
}
}
sleep(30);
printf("killer exit \n");
pthread_exit(NULL);
}
结果:
1 live
2 live
3 live
1 live
2 live
3 live
1 live
2 live
3 live
Terminated