Advertisement
Guest User

2.c

a guest
Aug 31st, 2015
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <pthread.h>
  5.  
  6. typedef struct _sync_int{
  7.     int v;
  8.     pthread_mutex_t lock;
  9. }sync_int;
  10.  
  11. sync_int n;
  12. char fname[32];
  13.  
  14. void* fun(void* arg){
  15.     int br=*(int*) arg;
  16.     int curr;
  17.     FILE* f;
  18.     f=fopen(fname, "r+");
  19.    
  20.     while(fscanf(f, "%d", &curr)==1){
  21.         if(curr==br){
  22.             pthread_mutex_lock(&n.lock);
  23.             n.v++;
  24.             pthread_mutex_unlock(&n.lock); 
  25.         }
  26.     }
  27.    
  28.     return (void*)0;
  29. }
  30.  
  31. int main(int argc, char** argv){
  32.     int i;
  33.     int args[10];
  34.     pthread_t pid_a[10];
  35.     n.v=0;
  36.     strcpy(fname, argv[1]);
  37.    
  38.     pthread_mutex_init(&n.lock, NULL);
  39.  
  40.     for(i=0;i<10;i++){
  41.         args[i]=i;
  42.         pthread_create(&pid_a[i], NULL, fun, &args[i]);
  43.     }
  44.    
  45.     for(i=0;i<10;i++)
  46.         pthread_join(pid_a[i], NULL);
  47.    
  48.     pthread_mutex_destroy(&n.lock);
  49.  
  50.     printf("%d\n", n.v);
  51.  
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement