由于最近到上海找工作不是很顺利,发现自己仍需不断学习。这里仅对线程同步做简单记录:
1:通过加锁来进行线程同步
涉及函数:
pthread_mutex_init
pthread_mutex_lock
pthread_mutex_unlock
简单测试代码:
1 #include <stdio.h>
3 #include <pthread.h>
4 typedef enum{ true=1,false=0 } bool;
5 char buffer[128];
6 bool buffer_has_data = false;
7 pthread_mutex_t mutex;
8
9 void write_buffer(char *data)
10 {
11 pthread_mutex_lock(&mutex);
12 if (!buffer_has_data)
13 {
14 sprintf(buffer, "%s", data);
15 buffer_has_data = true;
16 }
17 pthread_mutex_unlock(&mutex);
18 }
19 void read_buffer(void)
20 {
21 while (1)
22 {
23 pthread_mutex_lock(&mutex);
24 if (buffer_has_data)
25 {
26 printf("Read buffer, data = [%s]\n", buffer);
27 buffer_has_data = false;
28 }
29 pthread_mutex_unlock(&mutex);
30 sleep(1);
31 }
32 }
34 int main( int argc, char **argv)
35 {
36 char input[128];
37 pthread_t reader;
38
39 pthread_mutex_init(&mutex, NULL);
40 pthread_create(&reader, NULL, (void *)(read_buffer), NULL);
41
42 while (1)
43 {
44 scanf("%s", input);
45 write_buffer(input);
46 }
47 return 0;
48 }