Guest User

Untitled

a guest
May 20th, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <error.h>
  4.  
  5. #define NTHREADS 4
  6. static int k = 0;
  7.  
  8. struct thread_info{
  9. pthread_t thread_id;
  10. pthread_mutex_t lock;
  11. int x;
  12. int a[10];
  13. };
  14.  
  15. void* fkt(void* arg){
  16. struct thread_info* tinfo = (struct thread_info*) arg;
  17.  
  18. if(pthread_mutex_lock(&tinfo->lock)) perror("mutex_lock");
  19.  
  20. printf("THREAD %d with argument %dn", (int) tinfo->thread_id, tinfo->x);
  21.  
  22. tinfo->a[k] = tinfo->x * tinfo->x;
  23. k++;
  24.  
  25. if(pthread_mutex_unlock(&tinfo->lock)) perror("mutex_unlock");
  26.  
  27. pthread_exit(NULL);
  28. }
  29.  
  30. int main(){
  31. struct thread_info* tinfo = NULL;
  32.  
  33. tinfo->x = 5;
  34.  
  35. if(pthread_mutex_init(&tinfo->lock, NULL)) perror("mutex_init");
  36.  
  37. for(int i = 0; i < NTHREADS; i++){
  38. if(pthread_create(&tinfo[i].thread_id, NULL, &fkt, &tinfo)) perror("pthread_create");
  39. }
  40. for(int i = 0; i < NTHREADS; i++){
  41. if(pthread_join(tinfo[i].thread_id, NULL)) perror("pthread_join");
  42. printf("THREAD JOINED: %dn", (int) tinfo->thread_id);
  43. }
  44. for(int i = 0; i < 10; i++){
  45. printf("[%d]t", tinfo->a[i]);
  46. }
  47. printf("n");
  48.  
  49. if(pthread_mutex_destroy(&tinfo->lock)) perror("mutex_destroy");
  50.  
  51. return 0;
  52. }
Add Comment
Please, Sign In to add comment