Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2014
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <semaphore.h>
  6.  
  7. void myfunc1(void *ptr);
  8. void myfunc2(void *ptr);
  9.  
  10. char buf[24];
  11. sem_t mutex;
  12.  
  13. int main(int argc, char *argv[])
  14. {
  15. pthread_t thread1;
  16. pthread_t thread2;
  17.  
  18. char *msg1 = "Thread 1";
  19. char *msg2 = "Thread 2";
  20.  
  21. sem_init(&mutex, 0, 1);
  22.  
  23. pthread_create (&thread1, NULL, (void *) myfunc1, (void *)msg1);
  24. pthread_create (&thread2, NULL, (void *) myfunc2, (void *)msg2);
  25.  
  26. pthread_join(thread1, NULL);
  27. pthread_join(thread2, NULL);
  28.  
  29. sem_destroy(&mutex);
  30.  
  31. return 0;
  32. }
  33.  
  34. void myfunc1(void *ptr)
  35. {
  36. char *msg = (char *)ptr;
  37. printf("%s\n",msg);
  38. sem_wait(&mutex);
  39. sprintf(buf,"%s", "Hello There!");
  40. sem_post(&mutex);
  41. pthread_exit(0);
  42. }
  43.  
  44. void myfunc2(void *ptr)
  45. {
  46. char *msg = (char *)ptr;
  47. printf("%s\n",msg);
  48. sem_wait(&mutex);
  49. printf("%s\n",buf);
  50. sem_post(&mutex);
  51. pthread_exit(0);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement