H7N9禽流感来啦,多人死亡,又感觉到了03年我在北京时的非典气氛。
家里菜桌上肉明显没了。
睡一觉起来,肚子里再没有肉货,清明节学习的计划不能停止!!!
现在进入多线程学习啦。
由于LINUX进程间的通信占用资源蛮大的,所以设置了线程函数,只复制栈,其它同享。
当然,线程之间,也存在着同步机制啦:互斥锁,读写锁,条件变量等。。
硬件原理上还不是在作任何操作前,先检测内存的相关标志位的设置。。。。
一通百通的事儿。。。
1 [root@localhost ~]# cat pthread_cancle_exp.c 2 #include <stdio.h> 3 #include <unistd.h> 4 #include <stdlib.h> 5 #include <pthread.h> 6 void *thread_function(void *arg); 7 int main(int argc, char *argv[]) 8 { 9 int res; 10 pthread_t a_thread; 11 void *thread_result; 12 res = pthread_create(&a_thread, NULL, thread_function, NULL); 13 if(res != 0) 14 { 15 perror("Thread creation failed."); 16 exit(EXIT_FAILURE); 17 } 18 sleep(10); 19 printf("Canclling thread...\n"); 20 res = pthread_cancel(a_thread); 21 if(res != 0) 22 { 23 perror("Thread cancel failed\n"); 24 exit(EXIT_FAILURE); 25 } 26 printf("Waiting for thread to finish...\n"); 27 res = pthread_join(a_thread, &thread_result); 28 if(res != 0) 29 { 30 perror("Thread join failed."); 31 exit(EXIT_FAILURE); 32 } 33 exit(EXIT_SUCCESS); 34 } 35 36 void *thread_function(void *arg) 37 { 38 int i, res, j; 39 sleep(1); 40 res = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); 41 if(res != 0) 42 { 43 perror("Thread pthread_setcancelstate failed"); 44 exit(EXIT_FAILURE); 45 } 46 sleep(3); 47 printf("thread cancel type is disable ,can't cancle this thread\n"); 48 for(i = 0; i < 3; i++) 49 { 50 printf("Thread is running (%d)...\n", i); 51 sleep(1); 52 } 53 res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); 54 if (res != 0) 55 { 56 perror("Thread pthread_setcancelstate failed."); 57 exit(EXIT_FAILURE); 58 } 59 else 60 printf("Now change this cancelstate is ENABLE.\n"); 61 sleep(200); 62 pthread_exit(0); 63 }
输出:
[root@localhost ~]# ./pthread_cancle_exp
thread cancel type is disable ,can't cancle this thread
Thread is running (0)...
Thread is running (1)...
Thread is running (2)...
Now change this cancelstate is ENABLE.
Canclling thread...
Waiting for thread to finish...
LOOK到了没?当线程设置为不可取消时,THREAD 一直在RUN。
而当设置为可取消时,SLEEP(200)明显就没有执行啦。。