现在的位置: 首页 > 综合 > 正文

Linux创建线程

2017年12月19日 ⁄ 综合 ⁄ 共 2119字 ⁄ 字号 评论关闭

 

  1. #include"stdio.h"  
  2. #include"unistd.h"  
  3. #include"stdlib.h"  
  4. #include"pthread.h"  
  5. #include"semaphore.h"  
  6. #include"string.h"  
  7. void *thread_function(void *arg);  
  8. pthread_mutex_t work_mutex;  
  9.  
  10. #define WORK_SIZE 1024  
  11. char work_area[WORK_SIZE];  
  12. int time_to_exit=0;  
  13.  
  14. int main()  
  15. {  
  16.     int res;  
  17.     pthread_t a_thread;  
  18.     void *thread_result;  
  19.     res=pthread_mutex_init(&work_mutex,NULL);  
  20.     if(res!=0){  
  21.         perror("Mutex initialization failed");  
  22.         exit(EXIT_FAILURE);  
  23.     }  
  24.     res=pthread_create(&a_thread,NULL,thread_function,NULL);  
  25.     if(res!=0){  
  26.         perror("Thread creation failed!\n");  
  27.         exit(EXIT_FAILURE);  
  28.     }  
  29.       
  30.     pthread_mutex_lock(&work_mutex);  
  31.     printf("Input some text.Enter 'end' to finish\n");  
  32.     while(!time_to_exit){  
  33.         fgets(work_area,WORK_SIZE,stdin);  
  34.         pthread_mutex_unlock(&work_mutex);  
  35.         while(1){  
  36.             pthread_mutex_unlock(&work_mutex);  
  37.             if(work_area[0]!='\0'){  
  38.                 pthread_mutex_unlock(&work_mutex);  
  39.                 sleep(1);  
  40.             }  
  41.             else{  
  42.                 break;  
  43.             }  
  44.         }  
  45.         pthread_mutex_unlock(&work_mutex);  
  46.         printf("\nWaiting for thresd to finish...\n");  
  47.         res=pthread_join(a_thread,&thread_result);  
  48.         if(res!=0){  
  49.             perror("Thread join failed!\n");  
  50.             exit(EXIT_FAILURE);  
  51.         }  
  52.         printf("Thread joined!\n");  
  53.         pthread_mutex_destroy(&work_mutex);  
  54.         exit(EXIT_SUCCESS);  
  55.     }  
  56. }  
  57. void *thread_function(void *arg)  
  58. {  
  59.     sleep(1);  
  60.     pthread_mutex_lock(&work_mutex);  
  61.     while(strncmp("end",work_area,3)!=0){  
  62.         printf("You input %d chatacters\n",strlen(work_area)-1);  
  63.         work_area[0]='\0';  
  64.         pthread_mutex_lock(&work_mutex);  
  65.         sleep(1);  
  66.         pthread_mutex_lock(&work_mutex);  
  67.         while(work_area[0]=='\0'){  
  68.             pthread_mutex_unlock(&work_mutex);  
  69.             sleep(1);  
  70.             pthread_mutex_lock(&work_mutex);  
  71.         }  
  72.     }  
  73.     time_to_exit=1;  
  74.     work_area[0]='\0';  
  75.     pthread_mutex_unlock(&work_mutex);  
  76.     pthread_exit(0);  
  77. }  

 

本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/702535

【上篇】
【下篇】

抱歉!评论已关闭.