Guest User

Untitled

a guest
Jan 23rd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4.  
  5. #define N 3
  6.  
  7. int Counter = 0;
  8. pthread_mutex_t Mutex;
  9. pthread_t tid[N];
  10.  
  11. void* thr_inc_module(void* ptr){
  12. int* module = (int*)ptr;
  13.  
  14. while(Counter < 30){
  15. sleep(1);
  16.  
  17. pthread_mutex_lock(&Mutex);
  18. if(Counter % 3 == module[0]){
  19. printf("Thread: [%d] -- Counter=%d\n",*module,Counter++);
  20. }
  21.  
  22. pthread_mutex_unlock(&Mutex);
  23.  
  24. }
  25. return NULL;
  26. }
  27.  
  28.  
  29. int main(int argc, char *argv[]) {
  30. int i;
  31. int module[3];
  32.  
  33. pthread_mutex_init(&Mutex,NULL);
  34.  
  35. module[0] = 0;
  36. module[1] = 1;
  37. module[2] = 2;
  38.  
  39. for(i=0;i<N;i++){
  40. if (pthread_create(&tid[i], NULL, thr_inc_module, (void*)&module[i]) != 0) {
  41. printf("Error creating thread.\n");
  42. return -1;
  43. }
  44. }
  45.  
  46. for(i=0;i<N;i++){
  47. if(pthread_join(tid[i], NULL) != 0) {
  48. printf("Error joining thread.\n");
  49. return -1;
  50. }
  51. }
  52. return 0;
  53. }
Add Comment
Please, Sign In to add comment