C-マルチスレッド-キャンセルおよびキャンセルポイント
スレッドのキャンセル
コンパイル:
gcc -std=c99 -lpthread -o main main.c
deepfuture@deepfuture-laptop:~/mytest$ ./main
10000print:250
10000print:500
10000print:750
1add1
1chen1
thread 0はキャンセルされました!
thread 1はキャンセルされました!
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
thread 2はキャンセルできません!
deepfuture@deepfuture-laptop:~/mytest$
#include <pthread.h>
#include <stdio.h>
#define MAXTHREADS 3
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);
for (int i=1;i<*x;i++){
if ((i%250)==0) {// i 250
printf("%dprint:%d
",*x,i);
pthread_testcancel();//pthread_testcancel() , , ,
}
}
}
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
",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
",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 !
",i);
}
else{
printf("thread%d !
",i);
}
}
return(0);
}