/***********************************************
* This example shows how the ability to (easily)
* share memory between threads allows us to
* do some things very simply that were trouble-
* some in multi-process programs. This program
* prints an X on the screen endlessly. When the
* user presses a different letter key, that symbol
* is printed instead. Pressing q quits.
***********************************************/
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <termios.h>
void set_keypress(void);
/* Global variable's are shared amongst threads! */
char c = 'X';
/* The thread we create will execute this function. */
void* listenerThread(void * p)
{
while(scanf("%c",&c) == 1 && c != 'q')
;
exit(0); /* calling exit in a thread exits the whole process! */
}
int main()
{
set_keypress();
/* Create the listener thread */
pthread_t lt;
pthread_create(<,NULL,listenerThread,NULL);
/* Write character c forever! */
while(1)
{
printf(" %c",c);
fflush(stdout);
usleep(250000);
}
return 0;
}
/* This function changes the terminal settings
so that a) it's not line buffered and b) when
you press a key, nothing shows up on the screen.
*/
void set_keypress(void)
{
struct termios stored_settings;
struct termios new_settings;
tcgetattr( 0, &stored_settings);
new_settings = stored_settings;
new_settings.c_lflag &= (~ICANON);
new_settings.c_lflag &= (~ECHO);
new_settings.c_cc[VTIME] = 0;
new_settings.c_cc[VMIN] = 1;
tcsetattr( 0, TCSANOW, &new_settings);
}