OSSemPend是会把当前的任务挂起,直到另外一个任务的OSSemPost 运行完毕都得到Sem。但是可以通过改变OSSemCreate(x)里面的值x改变这种局面,当x不为0时,OSSemPend会马上得到Sem继续运行当前任务至结束,并将x的数值减一,直到为0。为0后,只有等其他任务的OSSemPost了。
任务2输出5之后,由于等待信号量被挂起,之后任务1输出3,然后发信号量,注意发信号亮并不是简单的+1,OSSemPost中有这几行代码if (pevent->OSEventGrp != 0) {
(void)OS_EventTaskRdy(pevent, (void *)0, OS_STAT_SEM, OS_STAT_PEND_OK)
OS_EXIT_CRITICAL()
OS_Sched()
return (OS_ERR_NONE)
}
此时因为任务2的优先级较1低,所以没有立即运行,而是任务1继续输出4、0然后挂起自己,任务2就运行了,输出678
/*编译命令:gcc -o shm shm.c -g */2
3#include<sys/sem.h>
4#include<sys/ipc.h>
5
6#define SEGSIZE 1024
7#define READTIME 1
8
9union semum
10{
11int val
12struct semid_ds *buf
13unsigned short *array
14}arg
15
16/* 创建信号量 */
17int sem_creat(key_t key)
18{
19union semun sem
20int semid
21sem.val = 0
22semid = semget(key, 1, IPC_CREAT | 0666)
23
24if (semid == -1)
25{
26printf("Create semaphore error\n")
27exit(-1)
28}
29
30semctl(semid, 0, SETVAL, sem)
31
32return semid
33}
34
35/* 删除信号量*/
36int del_sem(int semid)
37{
38union semun sem
39sem.val = 0
40semctl(semid, 0, IPC_RMID, sem)
41}
42
43/* 信号量的P操作,使得信号量的值加1 */
44int p(int semid)
45{
46struct sembuf sops = {0,
47 +1,
48 IPC_NOWAIT
49 }
50
51return (semop(semid, &sops, 1))
52}
53
54/* 信号量的v操作,使得信号量的值减1 */
55int v(int semid)
56{
57struct sembuf sops = {0,
58 -1,
59 IPC_NOWAIT
60 }
61
62return (semop(semid, &sops, 1))
63}
64
65/* server主程序 */
66int main(int argc, char **argv)
67{
68key_tkey
69int shmid, semid
70char *shm
71char msg[7] = "-data-"
72char i
73struct semid_ds buf
74
75key = ftok("/", 0)
76shmid = shmget(key, SEGSIZE, IPC_CREAT|0604)
77
78if shmid == -1)
79{
80printf(" create shared memory error\n")
81return -1
82}
83
84shm = (char *)shmat(shmid, 0, 0)
85if (-1 == (int)shm)
86{
87printf(" attach shared memory error\n")
88return -1
89}
90
91semid = sem_creat(key)
92
93for (i = 0i <= 3i++)
94{
95sleep(1)
96p(semid)
97sleep(READTIME)
98msg[5] = '0' + i
99memcpy(shm,msg,sizeof(msg))
100sleep(58)
101v(semid)
102}
103
104shmdt(shm)
105
106shmctl(shmid,IPC_RMID,&buf)
107
108del_sem(semid)
109
110return 0
111
112}
113
114
115
116
117
118
119
120
121
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)