Linux网络编程:生产者消费者问题


Linux网络编程:生产者消费者问题

  1. /************************************************* 
  2. * File name   :  
  3. * Description :  
  4. * Author      : sg131971@qq.com 
  5. * Version     : V1.0 
  6. * Date        :  
  7. * Compiler    : arm-linux-gcc-4.4.3 
  8. * Target      : mini2440(Linux-2.6.32) 
  9. * History     :  
  10. *   <author>  <time>   <version >   <desc> 
  11. *************************************************/  
  12. #include <stdio.h>   
  13. #include <pthread.h>   
  14. #include <semaphore.h>   
  15.   
  16. void *producter_f(void *arg);  
  17. void *consumer_f(void *arg);  
  18.   
  19. int buffer_has_item = 0;  
  20.   
  21. sem_t sem;  
  22.   
  23. int running = 1;  
  24.   
  25. /************************************************* 
  26. * Function    :  
  27. * Description :  
  28. * Calls       :  
  29. * Called By   :  
  30. * Input       :  
  31. * Output      :  
  32. * Return      :  
  33. *************************************************/  
  34. int main(void)  
  35. {  
  36.     pthread_t consumer_t;  
  37.     pthread_t producter_t;  
  38.   
  39.     sem_init(&sem, 0, 16);  
  40.   
  41.     pthread_create(&producter_t, NULL, (void *)producter_f, NULL);  
  42.     pthread_create(&consumer_t, NULL, (void *)consumer_f, NULL);  
  43.     sleep(1);  
  44.     running = 0;  
  45.     pthread_join(consumer_t, NULL);  
  46.     pthread_join(producter_t, NULL);  
  47.     sem_destroy(&sem);  
  48.   
  49.     return 0;  
  50. }  
  51.   
  52. /************************************************* 
  53. * Function    :  
  54. * Description :  
  55. * Calls       :  
  56. * Called By   : main 
  57. * Input       :  
  58. * Output      :  
  59. * Return      :  
  60. *************************************************/  
  61. void *producter_f(void *arg)  
  62. {  
  63.     int semval = 0;  
  64.     while (running)  
  65.     {  
  66.         usleep(10);  
  67.         sem_post(&sem);  
  68.         sem_getvalue(&sem, &semval);  
  69.         printf("生产,总数量:%d\n", semval);  
  70.     }  
  71. }  
  72.   
  73. /************************************************* 
  74. * Function    :  
  75. * Description :  
  76. * Calls       :  
  77. * Called By   : main 
  78. * Input       :  
  79. * Output      :  
  80. * Return      :  
  81. *************************************************/  
  82. void *consumer_f(void *arg)  
  83. {  
  84.     int semval = 0;  
  85.     while (running)  
  86.     {  
  87.         usleep(1);  
  88.         sem_wait(&sem);  
  89.         sem_getvalue(&sem, &semval);  
  90.         printf("消费,总数量:%d\n", semval);  
  91.     }  
  92. }  

相关内容