Скачиваний:
17
Добавлен:
01.05.2014
Размер:
1.57 Кб
Скачать
#include <iostream.h>
#include <thread.h>
#include <string.h>
#include <stdio.h>
#include <signal.h>

#define FINISH()   { cerr << (int)thr_self() << " exits\n"; \
                     mutex_unlock(&mutx); thr_exit(0); return 0; }

mutex_t mutx;
cond_t  condx;
int     msglen, done;
char    msgbuf[256];

void* writer (void* argp )
{
    do {
       mutex_lock(&mutx);
       while (!msglen) {
           cond_wait(&condx,&mutx);
           if (done) FINISH();
       }
       cout << "*> " << msgbuf << endl;
       msglen = 0;
       mutex_unlock(&mutx);
    } while (1);

    FINISH();
}

void* reader (void* argp )
{
    do {
       mutex_lock(&mutx);
       if (!msglen) {
          if (!cin.getline(msgbuf,256)) break;
          //if (cin.eof()) break;
          msglen = strlen(msgbuf)+1;
          cond_signal(&condx);
       } 
       else thr_yield();
       mutex_unlock(&mutx);
    } while (1);

    FINISH();
}
    
main() {
   thread_t wtid, rtid, tid;

   mutex_init(&mutx, USYNC_PROCESS, 0);
   cond_init(&condx, USYNC_PROCESS, 0);

   /* create a writer thread */
   if (thr_create(0,0,writer,0,0,&wtid))
      perror("thr_create");

   /* create a read thread */
   if (thr_create(0,0,reader,0,0,&rtid))
      perror("thr_create");

   /* wait for read process to exit */
   if (!thr_join(rtid,&tid,0))
   {
       done = 1;
       cond_signal(&condx);
   }

   /* clean up */  
   mutex_destroy(&mutx);
   cond_destroy(&condx);

   thr_exit(0);

   return 0;
}

   

   
Соседние файлы в папке pipes