TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Jasen Betts
from: Neil Heller
date: 2003-06-03 18:16:02
subject: Keyboard questions

NH> Also, the idea about having all keyboard input done in a thread
NH> works like a charm.

JB> not my idea there... I'm still scared of threads
JB> can you post example code?

This is completely untested - I'm writing this in an NT session but only 
do pthreads in *nix.  I guess I'm too lazy to keep rebooting.

#include 
#include 
#include 

pthread_mutex_t   my_mutex  = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t    its_there = PTHREAD_COND_INITIALIZER;

int   there = 0;
char  foo[50];

void * reader_func(void * unused)
{
   while ( 1 ) {
      pthread_mutex_lock( &my_mutex )
      while (!there)
         pthread_cond_wait( &its_there, &my_mutex );
      printf("And it was written: %s", foo);
      there = 0;
      pthread_mutex_unlock( &my_mutex );
   }
}


void * writer_func(void * unused)
{
   while ( 1 ) {
      pthread_mutex_lock( &my_mutex );
      printf( "Enter a wise saying: ");
      fgets( foo, 49, stdin );
      there = 1;
      pthread_cond_signal( &its_there );
      pthread_mutex_unlock( &my_mutex );
      if (strstr( foo, "foo" )) there = 2;
   }
}


int main(void)
{
   pthread_t        first_thread, second_thread;
   char             ch;
   struct timespec  req, rem;

   req.tv_sec = 5;
   req.tv_nsec = 0;

   pthread_create(&first_thread,  NULL, reader_func, NULL);
   pthread_create(&second_thread, NULL, writer_func, NULL);

   while ( there < 2 ) { nanosleep( &req, &rem }
}


This code will check every 5 seconds to see if the user has typed "foo" 
anywhere in his wise saying.  Then all the threads will be terminated 
and the program will end.

I realize that this is a simplistic example, filled with magic numbers 
and will work correctly only on a *nix system.

þ CMPQwk 1.42 999

--- Maximus/2 3.01
* Origin: COMM Port OS/2 juge.com 204.89.247.1 (281) 980-9671 (1:106/2000)
SEEN-BY: 633/267 270
@PATH: 106/2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.