歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Linux下對信號量測試的一個簡單例子

Linux下對信號量測試的一個簡單例子:

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <pthread.h>  
  4. #include <semaphore.h>  
  5.  
  6. #define MAXSTACK 100  
  7. int stack[MAXSTACK][2]; 
  8. int size = 0; 
  9. sem_t sem; 
  10.  
  11. void ReadData1(void) 
  12. { 
  13.     FILE *fp = fopen("1.dat","r"); 
  14.     if(fp == NULL) 
  15.     { 
  16.         printf("Open file error\n"); 
  17.         return; 
  18.     } 
  19.     while(!feof(fp)) 
  20.     { 
  21.         fscanf(fp,"%d %d",&stack[size][0],&stack[size][1]); 
  22.         sem_post(&sem); 
  23.         ++size; 
  24.     } 
  25.     if(fp != NULL) 
  26.     fclose(fp); 
  27. } 
  28.  
  29. void ReadData2(void) 
  30. { 
  31.     FILE *fp = fopen("2.dat","r"); 
  32.     if(fp == NULL) 
  33.     { 
  34.         printf("Open file ERROR\n"); 
  35.         return; 
  36.     } 
  37.     while(!feof(fp)) 
  38.     { 
  39.         fscanf(fp,"%d %d",&stack[size][0],&stack[size][1]); 
  40.         sem_post(&sem); 
  41.         ++size; 
  42.     } 
  43.     if(fp != NULL) 
  44.         fclose(fp); 
  45. } 
  46.  
  47. void HandleData1(void) 
  48. { 
  49.     while(1) 
  50.     { 
  51.         sem_wait(&sem); 
  52.         printf("Plus:%d+%d=%d\n",stack[size][0],stack[size][1],stack[size][0]+stack[size][1]); 
  53.         --size; 
  54.     } 
  55. } 
  56.  
  57. void HandleData2(void) 
  58. { 
  59.     while(1) 
  60.     { 
  61.         sem_wait(&sem); 
  62.         printf("Multiply:%d*%d=%d\n",stack[size][0],stack[size][1],stack[size][0]*stack[size][1]); 
  63.         --size; 
  64.     } 
  65. } 
  66.  
  67.  
  68. int main(void) 
  69. { 
  70.     pthread_t t1,t2,t3,t4; 
  71.     sem_init(&sem,0,0); 
  72.     pthread_create(&t1,NULL,(void *)HandleData1,NULL); 
  73.     pthread_create(&t2,NULL,(void *)HandleData2,NULL); 
  74.     pthread_create(&t3,NULL,(void *)ReadData1,NULL); 
  75.     pthread_create(&t4,NULL,(void *)ReadData2,NULL); 
  76.     pthread_join(t1,NULL); 
  77. } 
Copyright © Linux教程網 All Rights Reserved