#include <pthread.h> #include <unistd.h> #include <stdio.h> void *thread(void *str) { int i; for (i = 0; i < 3; ++i) { sleep(2); printf( "This in the thread : %dn" , i ); } return NULL; }
int main() { pthread_t pth; int i;
/*创建线程并执行线程执行函数*/ int ret = pthread_create(&pth, NULL, thread, NULL); printf("The main process will be to run,but will be blocked soonn"); /*阻塞等待线程退出*/ pthread_join(pth, NULL);
printf("thread was exitn"); for (i = 0; i < 3; ++i) { sleep(1); printf( "This in the main : %dn" , i ); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <pthread.h>
void mythread() { int i; for(i=0;i<3;i++) { printf("this is a pthread:n"); } pthread_exit("thank you for the cpu timen"); }
int main() { pthread_t id; int i,ret; void *thread_result; ret=pthread_create(&id,NULL,(void *)mythread,NULL); if(ret!=0) { printf("create pthread errorn"); exit(1); } for(i=0;i<3;i++) { printf("this is the main:n"); } pthread_join(id,&thread_result); printf("thread joined, it returned:%s",(char *)thread_result); return 0; }
#include <stdio.h> #include <stdlib.h> #include <pthread.h>
void mythread() { int i,ret; ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL); if(ret!=0) { printf("thread pthread_setcancelstate failedn"); exit(1); } ret = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL); if(ret!=0) { printf("thread pthread_setcanceltype failedn"); exit(1); } for(i=0;i<10;i++) { printf("this is a pthread:n"); sleep(1); } pthread_exit("thank you for the cpu timen"); }
int main() { pthread_t id; int ret; void *thread_result; ret=pthread_create(&id,NULL,(void *)mythread,NULL); if(ret!=0) { printf("create pthread errorn"); exit(1); } sleep(3); printf("cancleing thread....n"); ret = pthread_cancel(id); if(ret!=0) { printf("thread pthread_cancel failedn"); exit(1); } sleep(2); pthread_join(id,&thread_result); printf("thread joined, it returned:%s",(char *)thread_result); return 0; }
|