«  6.6. Implicit Threading and Language-based Threads   ::   Contents   ::   6.8. Extended Example: Concurrent Prime Number Search  »

6.7. Extended Example: Keyboard Input Listener

This example illustrates how threads can be created to perform a particular task. This style of multithreading forms the basis of programs that have graphical user interfaces. Specifically, the example shown here acts as a custom keyboard event listener; the child thread continually reads from the keyboard until the user enters exactly a 7. Similarly, programs with mouse event handlers use threads specifically for that purpose.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <assert.h>

#define MAX_LENGTH 40

void flush_buffer (char *buffer);

void *
keyboard_listener (void *args)
{
  char buffer[MAX_LENGTH + 1];
  memset (buffer, 0, MAX_LENGTH + 1);

  /* Read a line of input from STDIN */
  while (fgets (buffer, MAX_LENGTH, stdin) != NULL)
    {
      /* Try to convert input to integer 7. All other values
         are wrong. */
      long guess = strtol (buffer, NULL, 10);
      if (guess != 7)
        {
          printf ("Wrong. Try again. ");
          /* Clear the buffer for another try. */
          flush_buffer (buffer);
          memset (buffer, 0, MAX_LENGTH);
        }
      else
        {
          /* Successfully read a 7 from input; exit with true */
          printf ("Congratulations!\n");
          pthread_exit ((void*)true);
        }
    }

  /* In case input fails for some reason, exit thread with false */
  pthread_exit ((void*)false);
}


int
main (int argc, char **argv)
{
  pthread_t guess;
  printf ("Guess a number between 1 and 10: ");

  /* Create a thread that reads until a 7 is input and exits. */
  assert (pthread_create (&guess, NULL, keyboard_listener, NULL)
          == 0);

  /* Wait until the thread exits */
  void *result;
  pthread_join (guess, &result);

  if (result)
    printf ("You must have guessed 7.\n");

  return 0;
}


/* Helper function for reading input. If the input line was too
   long (so no '\n' was read), clear out the rest of the input to 
   try again. */
void
flush_buffer (char *buffer)
{
  int chr;
  
  /* Check for '\n' */
  char *newline = strchr (buffer, '\n');

  /* If none found, retrieve and discard rest of the characters */
  if (newline == NULL)
    while (((chr = getchar()) != '\n') && !feof (stdin) &&
           !ferror (stdin))
      ;
}
«  6.6. Implicit Threading and Language-based Threads   ::   Contents   ::   6.8. Extended Example: Concurrent Prime Number Search  »

Contact Us License