gcc -lpthread -std=c99 -o main main.c
deepfuture@deepfuture-laptop:~/mytest$ ./main
1chen1
2chen2
3chen6
4chen24
5chen120
6chen720
7chen5040
8chen40320
9chen362880
10chen3628800
11chen39916800
12chen479001600
13chen1932053504
14chen1278945280
15chen2004310016
16chen2004189184
17chen-288522240
18chen-898433024
19chen109641728
20chen-2102132736
21chen-1195114496
22chen-522715136
23chen862453760
24chen-775946240
25chen2076180480
1add1
10000print:250
clear:10000
thread0 已经取消!
thread1 已经取消!
thread2 不能被取消!
#include <pthread.h> #include <stdio.h> #define MAXTHREADS 3 void *myclear(void *x){ printf("clear:%d\n",*((int*)x)); } void *mycompprint(void *xx){//参数必须为void *,然后进行强制类型转换 int oldstate,oldtype; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,&oldstate);//设置线程是可以中止的。 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,&oldtype);//设置线程推迟中止,PTHREAD_CANCEL_DEFERRED为默认值。 int *x=(int *)(xx); void *xxx=(void *)x; pthread_cleanup_push(myclear,xxx);//压入线程清理堆栈,堆栈包含指向取消过程中执行例程的指针,即中止前执行一个清理。myclear为例程名,x为传给例程的参数 for (int i=1;i<*x;i++){ if ((i%250)==0) {//如果i为250的倍数则取消 printf("%dprint:%d\n",*x,i); pthread_testcancel();//pthread_testcancel()检测是否需要取消,设置取消点,如果有挂起的取消请求,则在此处中止本线程 } } pthread_cleanup_pop(0); //从调用线程清理堆栈的顶部移走清理函数指针,但并不执行它,pthread_testcancel()检测不到取消请求,表示目前不需要取消,所以移走它。pthread_cleanup_pop(1)移走并执行它,即使并没有中止线程; } void *mycompadd(void *xx){//参数必须为void *,然后进行强制类型转换 int oldstate,oldtype; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,&oldstate);//设置线程是可以中止的。 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&oldtype);//设置线程线程立即中止,PTHREAD_CANCEL_ASYNCHRONOUS表示线程立即终止。 int sum=0; int *x=(int *)(xx); int y; for (int i=1;i<=*x;i++){ sum+=i; printf("%dadd%d\n",i,sum); } } void *mycompchen(void *xx){//参数必须为void *,然后进行强制类型转换 int oldstate,oldtype; pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,&oldstate);//设置线程不能中止的。 int sum=1; int *x=(int *)(xx); for (int i=1;i<=*x;i++){ sum*=i; printf("%dchen%d\n",i,sum); } } int main(){ //线程分离后,不能再合并 //main为boss线程, pthread_t threads[MAXTHREADS];//创建线程池 void *status; //创建worker线程,并执行线程 int n1=25; int n2=10000; //深未来技术原创,http://deepfuture.iteye.com pthread_create(&(threads[0]),NULL,mycompprint,&n2); pthread_create(&(threads[1]),NULL,mycompadd,&n1); pthread_create(&(threads[2]),NULL,mycompchen,&n1); for (int i=0;i<MAXTHREADS;i++){ pthread_cancel(threads[i]); } for (int i=0;i<MAXTHREADS;i++){ pthread_join(threads[i],&status); //wait worker线程,并合并到BOSS线程来 if (status==PTHREAD_CANCELED){ printf("thread%d 已经取消!\n",i); } else{ printf("thread%d 不能被取消!\n",i); } } return(0); }