标签:
1 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
1 #include <stdio.h> 2 #include <unistd.h> 3 #include <pthread.h> 4 5 void thread_function(void *param) 6 { 7 printf("this is a thread.\n"); 8 } 9 int thread_test(void) 10 { 11 pthread_t thread_id; 12 int ret; 13 ret = pthread_create(&thread_id, NULL, (void *)&thread_function, NULL); 14 if(ret != 0) { 15 printf("pthread_create fail\n"); 16 return -1; 17 } 18 19 /*主要是为了看到线程的打印*/ 20 sleep(1); 21 22 } 23 int main(int argc, char *argv[]) 24 { 25 thread_test(); 26 return 0; 27 }
线程退出函数原型:
1 void pthread_exit(void *retval);
1 int pthread_join(pthread_t thread, void **retval);
1 #include <stdio.h> 2 #include <unistd.h> 3 #include <pthread.h> 4 pthread_t thread1_id, thread2_id; 5 void thread_function1(void *param) 6 { 7 printf("this is a thread 2.\n"); 8 while(1) { 9 printf("thread 1 is running.\n"); 10 sleep(1); 11 } 12 printf("thread 1 exit.\n"); 13 } 14 void thread_function2(void *param) 15 { 16 printf("this is a thread 2.\n"); 17 sleep(2); 18 printf("thread 2 cancel thread 1.\n"); 19 pthread_cancel(thread1_id); 20 } 21 int thread_test(void) 22 { 23 int ret; 24 ret = pthread_create(&thread1_id, NULL, (void *)&thread_function1, NULL); 25 if(ret != 0) { 26 printf("pthread_create fail\n"); 27 return -1; 28 } 29 ret = pthread_create(&thread1_id, NULL, (void *)&thread_function2, NULL); 30 if(ret != 0) { 31 printf("pthread_create fail\n"); 32 return -1; 33 } 34 ret = pthread_join(thread1_id, NULL); 35 if(ret != 0) { 36 printf("pthread_join fail\n"); 37 return -1; 38 } 39 } 40 int main(int argc, char *argv[]) 41 { 42 thread_test(); 43 return 0; 44 }
1 int pthread_cancel(pthread_t thread);
1 #include <stdio.h> 2 #include <unistd.h> 3 #include <pthread.h> 4 pthread_t thread1_id, thread2_id; 5 void thread_function1(void *param) 6 { 7 printf("this is a thread 2.\n"); 8 while(1) { 9 printf("thread 1 is running.\n"); 10 sleep(1); 11 } 12 printf("thread 1 exit.\n"); 13 } 14 void thread_function2(void *param) 15 { 16 printf("this is a thread 2.\n"); 17 sleep(2); 18 printf("thread 2 cancel thread 1.\n"); 19 pthread_cancel(thread1_id); 20 } 21 int thread_test(void) 22 { 23 int ret; 24 ret = pthread_create(&thread1_id, NULL, (void *)&thread_function1, NULL); 25 if(ret != 0) { 26 printf("pthread_create fail\n"); 27 return -1; 28 } 29 ret = pthread_create(&thread1_id, NULL, (void *)&thread_function2, NULL); 30 if(ret != 0) { 31 printf("pthread_create fail\n"); 32 return -1; 33 } 34 ret = pthread_join(thread1_id, NULL); 35 if(ret != 0) { 36 printf("pthread_join fail\n"); 37 return -1; 38 } 39 } 40 int main(int argc, char *argv[]) 41 { 42 thread_test(); 43 return 0; 44 }
只是简单的介绍了下线程的基本操作,更高级的应用稍后更新敬请期待~~
标签:
原文地址:http://www.cnblogs.com/zSir-2015/p/4890483.html