Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 19th, 2012  |  syntax: None  |  size: 1.10 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4. #include <stdlib.h>
  5.  
  6. #define TRUE 1
  7. #define FALSE 0
  8.  
  9. char n[1024];
  10. pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER;
  11. int string_read=FALSE;
  12.  
  13. pthread_cond_t cond;
  14.  
  15. void * read1()
  16. {
  17.         while(1){
  18.                 while(string_read);
  19.                 pthread_mutex_lock(&lock);
  20.                 printf("Enter a string: ");
  21.                 scanf("%s",n);
  22.                 string_read=TRUE;
  23.                 pthread_mutex_unlock(&lock);
  24.                 pthread_cond_signal(&cond);
  25.         }
  26. }
  27.  
  28. void * write1()
  29. {
  30.         while(1){
  31.                 pthread_mutex_lock(&lock);
  32.                 while(!string_read)
  33.                         pthread_cond_wait(&cond,&lock);
  34.                         printf("The string entered is %s\n",n);
  35.  
  36.                         string_read=FALSE;
  37.                         pthread_mutex_unlock(&lock);
  38.         }
  39. }
  40. int main()
  41. {
  42.         int status;
  43.         pthread_t tr, tw;
  44.  
  45.         pthread_create(&tr,NULL,read1,NULL);
  46.         pthread_create(&tw,NULL,write1,NULL);
  47.  
  48.         pthread_join(tr,NULL);
  49.         pthread_join(tw,NULL);
  50.         return 0;
  51. }