Advertisement
Guest User

Untitled

a guest
May 22nd, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. //
  2. // thread_1.c
  3. //
  4. // pthread_create() - create a thread
  5. // pthread_join() - wait for termination of another thread
  6. //
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <pthread.h>
  11.  
  12. #define MAX_NUM 100 // maximum number of threads
  13.  
  14. int sum = 0;
  15.  
  16. pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
  17.  
  18. //
  19. // The thread start routine
  20. //
  21. void* f(void* a)
  22. {
  23. int k = *(int*)a;
  24.  
  25. srand(time(NULL));
  26. int n = rand() % 10;
  27.  
  28. while(sum <1000) {
  29. pthread_mutex_lock(&mtx);
  30. sum += n;
  31. if (sum >1000) {
  32. printf("Thread-ul %d a realizat trecerea",k);
  33. }
  34. pthread_mutex_unlock(&mtx);
  35. }
  36.  
  37. return NULL;
  38. }
  39.  
  40.  
  41.  
  42. int main(int argc, char* argv[])
  43. {
  44. pthread_t t[MAX_NUM]; // an array of threads
  45.  
  46. int index[5];
  47. for (int k = 0; k<5; k++) {
  48. index[k] = k;
  49. }
  50. int i;
  51. for (i = 0; i < MAX_NUM; i++)
  52. {
  53. pthread_create(&t[i], NULL, f, &index[i]); // create a thread
  54. }
  55.  
  56. for (i = 0; i < MAX_NUM; i++)
  57. {
  58. pthread_join(t[i], NULL); // wait for each thread to finish
  59. }
  60.  
  61.  
  62. return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement