Advertisement
Guest User

Untitled

a guest
May 25th, 2015
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <errno.h>
  4. #include <pthread.h>
  5. void do_one_thing(int *);
  6. void do_another_thing(int *);
  7. void do_wrap_up(int);
  8. int common = 0; /* A shared variable for two threads */
  9. pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER;
  10. main()
  11. {
  12. pthread_t thread1, thread2;
  13. if (pthread_create(&thread1, NULL, (void *)do_one_thing, (void *)&common)!=0)
  14. perror("pthread_create"),exit(1);
  15. if (pthread_create(&thread2,NULL,(void *)do_another_thing,(void *)&common)!=0)
  16. perror("pthread_create"),exit(1);
  17. if (pthread_join(thread1, NULL) != 0) perror("pthread_join"), exit(1);
  18. if (pthread_join(thread2, NULL) != 0) perror("pthread_join"), exit(1);
  19. do_wrap_up(common);
  20. return 0;
  21. }
  22. void do_one_thing(int *pnum_times)
  23. {
  24. int i, j, x;
  25. unsigned long k;
  26. int work;
  27. for (i=0;i<50;i++){
  28. pthread_mutex_lock(&mut);
  29. printf("doing one thing\n");
  30. work = *pnum_times;
  31. printf("counter = %d\n", work);
  32. work++; /* increment, but not write */
  33. for (k=0;k<500000;k++); /* long cycle */
  34. *pnum_times = work; /* write back */
  35. pthread_mutex_unlock(&mut);
  36. }
  37. }
  38. void do_another_thing(int *pnum_times)
  39. {
  40. int i, j, x;
  41. unsigned long k;
  42. int work;
  43. for (i=0;i<50;i++) {
  44. pthread_mutex_lock(&mut);
  45. printf("doing another thing\n");
  46. work = *pnum_times;
  47. printf("counter = %d\n", work);
  48. work++; /* increment, but not write */
  49. for (k=0;k<500000;k++); /* long cycle */
  50. *pnum_times = work; /* write back */
  51. pthread_mutex_unlock(&mut);
  52. }
  53. }
  54. void do_wrap_up(int counter)
  55. {
  56. int total;
  57. printf("All done, counter = %d\n", counter);
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement