Skip to content

Commit f2a41a7

Browse files
committed
更新读书记录 增加进程同步demo
1 parent 50aedeb commit f2a41a7

File tree

2 files changed

+501
-17
lines changed

2 files changed

+501
-17
lines changed

14. 进程同步demo/main.cpp

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#include <sys/sem.h>
2+
#include <sys/types.h>
3+
#include <cstdlib>
4+
#include <unistd.h>
5+
#include <cstdio>
6+
7+
union semun
8+
{
9+
int val; /* Value for SETVAL */
10+
struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */
11+
unsigned short *array; /* Array for GETALL, SETALL */
12+
struct seminfo *__buf; /* Buffer for IPC_INFO(Linux-specific) */
13+
};
14+
15+
bool P(int sem_id)
16+
{
17+
struct sembuf sem_b;
18+
sem_b.sem_num = 0;
19+
sem_b.sem_op = -1; // P
20+
sem_b.sem_flg = SEM_UNDO;
21+
return semop(sem_id, &sem_b, 1) != -1;
22+
}
23+
24+
int V(int sem_id)
25+
{
26+
struct sembuf sem_b;
27+
sem_b.sem_num = 0;
28+
sem_b.sem_op = 1; // V
29+
sem_b.sem_flg = SEM_UNDO;
30+
return semop(sem_id, &sem_b, 1) != -1;
31+
}
32+
33+
int main(int argc, char *argv[])
34+
{
35+
char message = 'x';
36+
37+
int sem_id = semget((key_t) 1234, 1, 0666 | IPC_CREAT);
38+
39+
// 初次调用程序初始化信号量
40+
if (argc > 1)
41+
{
42+
// 初始化信号量
43+
union semun sem_union;
44+
sem_union.val = 1;
45+
46+
if (semctl(sem_id, 0, SETVAL, sem_union) == -1)
47+
{
48+
exit(0);
49+
}
50+
message = argv[1][0];
51+
sleep(2);
52+
}
53+
54+
for (int i = 0; i < 10; ++i)
55+
{
56+
if (!P(sem_id))
57+
{
58+
exit(EXIT_FAILURE);
59+
}
60+
// 打印自己的特有message
61+
printf("%c", message);
62+
fflush(stdout);
63+
64+
sleep(rand() % 3);
65+
66+
printf("%c", message);
67+
fflush(stdout);
68+
69+
if (!V(sem_id))
70+
{
71+
exit(EXIT_FAILURE);
72+
}
73+
}
74+
75+
sleep(2);
76+
printf("\n%d - finished\n", getpid());
77+
78+
// 初次调用完删除信号量
79+
if (argc > 1)
80+
{
81+
sleep(3);
82+
// 删除信号量
83+
union semun sem_union{};
84+
if (semctl(sem_id, 0, IPC_RMID, sem_union) == -1)
85+
{
86+
exit(EXIT_FAILURE);
87+
}
88+
}
89+
exit(EXIT_SUCCESS);
90+
}

0 commit comments

Comments
 (0)