复制代码代码如下: #include<stdio.h> #include<pthread.h></p><p>void *func1(void *arg){//原函数声明 int i; for(i=0;i<5;i++){ printf("this is func1! The num is %d
",*(int*)arg);//将空指针转换为int型指针 sleep(1); } }</p><p>void *func2(int *m){ //自定义类型声明,也可以定义非指针类型,但是在create时会有警告,因为非地址并不能改变传入的值 int i; for(i=0;i<5;i++){ printf("this is func2! The num is %d
",*m); (*m)++; sleep(1); } }</p><p>int main(){ pthread_t id1,id2; int num = 5; int *p = # if(pthread_create(&id1,NULL,(void *)func1,(void *)p) != 0){ printf("thread1 create error!
"); return -1; } if(pthread_create(&id2,NULL,(void *)func2,&num) != 0){ printf("thread2 create error!
"); return -1; } pthread_join(id1,NULL); //等待线程结束 pthread_join(id2,NULL); printf("Running complete!
"); return 0;</p><p> }
运行结果:
复制代码代码如下: [fsy@localhost process]$ gcc thC.c -o thC -lpthread -g [fsy@localhost process]$ ./thC this is func2! The num is 5 this is func1! The num is 6 this is func2! The num is 6 this is func1! The num is 7 this is func2! The num is 7 this is func1! The num is 8 this is func2! The num is 8 this is func1! The num is 9 this is func2! The num is 9 this is func1! The num is 10 Running complete! [fsy@localhost process]$
复制代码代码如下: #include<stdio.h> #include<pthread.h></p><p>void *clean(char *argv){ printf("clean is called by %s
",argv); return NULL; } void *func1(void *argv){ printf("welcome enter the func1!
"); pthread_cleanup_push((void*)clean,"the first time call!"); pthread_cleanup_push((void*)clean,"the second time call!"); if(argv){ return (void *)1;//第二次运行将此句注掉 } pthread_cleanup_pop(0); pthread_cleanup_pop(1); return (void *)0; }</p><p>void *func2(void *argv){ sleep(1); //两个线程运行先后不确定 printf("welcome enter the func2!
"); pthread_cleanup_push((void*)clean,"the first time call!"); pthread_cleanup_push((void*)clean,"the second time call!"); if(argv){ pthread_exit(NULL); } pthread_cleanup_pop(0); pthread_cleanup_pop(0); return (void *)0; }</p><p> int main(){ pthread_t tid1,tid2; if(pthread_create(&tid1,NULL,(void *)func1,(void *)1) != 0){ printf("thread1 create error!
"); return 1; }</p><p> if(pthread_create(&tid2,NULL,(void *)func2,(void *)1) != 0){ printf("thread2 create error!
"); return 1; } pthread_join(tid1,NULL); pthread_join(tid2,NULL); return 0; }
运行结果:
复制代码代码如下: [fsy@localhost process]$ gcc thClean.c -o thclean -lpthread [fsy@localhost process]$ ./thclean welcome enter the func1! welcome enter the func2! clean is called by the second time call!//此处先2后1 clean is called by the first time call! [fsy@localhost process]$ vim thClean.c [fsy@localhost process]$ gcc thClean.c -o thclean -lpthread [fsy@localhost process]$ ./thclean welcome enter the func1! clean is called by the first time call!//second已经被pop welcome enter the func2! clean is called by the second time call! clean is called by the first time call! [fsy@localhost process]$