Debian Codegraph @

listings/chapter-4/thread-create2.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <pthread.h>
8 #include <stdio.h>
9
10 /* Parameters to print_function. */
11
12 struct char_print_parms
13 {
14 /* The character to print. */
15 char character;
16 /* The number of times to print it. */
17 int count;
18 };
19
20 /* Prints a number of characters to stderr, as given by PARAMETERS,
21 which is a pointer to a struct char_print_parms. */
22
23 void* char_print (void* parameters)
24 {
25 /* Cast the cookie pointer to the right type. */
26 struct char_print_parms* p = (struct char_print_parms*) parameters;
27 int i;
28
29 for (i = 0; i < p->count; ++i)
30 fputc (p->character, stderr);
31 return NULL;
32 }
33
34 /* The main program. */
35
36 int main ()
37 {
38 pthread_t thread1_id;
39 pthread_t thread2_id;
40 struct char_print_parms thread1_args;
41 struct char_print_parms thread2_args;
42
43 /* Create a new thread to print 30000 x's. */
44 thread1_args.character = 'x';
45 thread1_args.count = 30000;
46 pthread_create (&thread1_id, NULL, &char_print, &thread1_args);
47
48 /* Create a new thread to print 20000 o's. */
49 thread2_args.character = 'o';
50 thread2_args.count = 20000;
51 pthread_create (&thread2_id, NULL, &char_print, &thread2_args);
52
53 /* Make sure the first thread has finished. */
54 pthread_join (thread1_id, NULL);
55 /* Make sure the second thread has finished. */
56 pthread_join (thread2_id, NULL);
57
58 /* Now we can safely return. */
59 return 0;
60 }