forked from hailinzeng/Programming-POSIX-Threads
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flock.c
84 lines (80 loc) · 2.31 KB
/
flock.c
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
82
83
84
/*
* flock.c
*
* Demonstrate use of stdio file locking to generate an "atomic"
* prompting sequence. The write to stdout and the read from
* stdin cannot be separated.
*/
#include <pthread.h>
#include "errors.h"
/*
* This routine writes a prompt to stdout (passed as the thread's
* "arg"), and reads a response. All other I/O to stdin and stdout
* is prevented by the file locks until both prompt and fgets are
* complete.
*/
void *prompt_routine (void *arg)
{
char *prompt = (char*)arg;
char *string;
int len;
string = (char*)malloc (128);
if (string == NULL)
errno_abort ("Alloc string");
flockfile (stdin);
flockfile (stdout);
printf (prompt);
if (fgets (string, 128, stdin) == NULL)
string[0] = '\0';
else {
len = strlen (string);
if (len > 0 && string[len-1] == '\n')
string[len-1] = '\0';
}
funlockfile (stdout);
funlockfile (stdin);
return (void*)string;
}
int main (int argc, char *argv[])
{
pthread_t thread1, thread2, thread3;
char *string;
int status;
#ifdef sun
/*
* On Solaris 2.5, threads are not timesliced. To ensure
* that our threads can run concurrently, we need to
* increase the concurrency level.
*/
DPRINTF (("Setting concurrency level to 4\n"));
thr_setconcurrency (4);
#endif
status = pthread_create (
&thread1, NULL, prompt_routine, "Thread 1> ");
if (status != 0)
err_abort (status, "Create thread");
status = pthread_create (
&thread2, NULL, prompt_routine, "Thread 2> ");
if (status != 0)
err_abort (status, "Create thread");
status = pthread_create (
&thread3, NULL, prompt_routine, "Thread 3> ");
if (status != 0)
err_abort (status, "Create thread");
status = pthread_join (thread1, (void**)&string);
if (status != 0)
err_abort (status, "Join thread");
printf ("Thread 1: \"%s\"\n", string);
free (string);
status = pthread_join (thread2, (void**)&string);
if (status != 0)
err_abort (status, "Join thread");
printf ("Thread 1: \"%s\"\n", string);
free (string);
status = pthread_join (thread3, (void**)&string);
if (status != 0)
err_abort (status, "Join thread");
printf ("Thread 1: \"%s\"\n", string);
free (string);
return 0;
}