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

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

sema_t  semx;
int     msglen, done;
char    msgbuf[256];

void* writer (void* argp )
{
    do {
       sema_wait(&semx);
       if (msglen) {
          cout << "*> " << msgbuf << endl;
          msglen = 0;
       }
       sema_post(&semx);
       thr_yield();
    } while (!done);

    FINISH();
}

void* reader (void* argp )
{
    do {
       sema_wait(&semx);
       if (!msglen) {
          if (cin.getline(msgbuf,256))
             msglen = strlen(msgbuf)+1;
          else done = 1;
       } 
       sema_post(&semx);
       thr_yield();
    } while (!done);

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

   sema_init(&semx, 1, 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 */
   while (!thr_join(0,0,0)) ;

   /* clean up */  
   sema_destroy(&semx);

   thr_exit(0);

   return 0;
}

   

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