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

rwlock_t rwlk;
int     msglen, done = 0;
char    msgbuf[256];

void* writer (void* argp )
{
    while (!done) {
       if (rw_rdlock(&rwlk)) perror("rw_rdlock");
       if (msglen) {
          cout << "*> " << msgbuf << endl;
          msglen = 0;
       }
       if (rw_unlock(&rwlk)) perror("rw_unlock(1)");
       //sleep(1);
       thr_yield();
    } 
    cerr << "write thread (" << (int)thr_self() << ") exits\n";
    thr_exit(0);
    return 0;
}

void* reader (void* argp )
{
    do {
       if (rw_wrlock(&rwlk)) perror("rw_wrlock");
       if (!msglen) {
          if (!cin.getline(msgbuf,256)) break;
          msglen = strlen(msgbuf)+1;
       } 
       if (rw_unlock(&rwlk)) perror("rw_unlock(2)");
       //sleep(1);
       thr_yield();
    } while (1);
    cerr << "read thread (" << (int)thr_self() << ") exits\n";
    if (rw_unlock(&rwlk)) perror("rw_unlock(3)");
    thr_exit(0);
    return 0;
}
    
main() {
   thread_t wtid, rtid, tid;

   if (rwlock_init(&rwlk, USYNC_PROCESS, 0)) {
       perror("rwlock_init");
       return 1;
   }

   /* 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;
   }

   /* clean up */  
   rwlock_destroy(&rwlk);

   thr_exit(0);
}

   

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