linux 多进程 同步,linux 多进程的同步和互斥

#include #include “semun.h”

static int set_semvalue(void);

static void del_semvalue(void);

static int semaphore_p(void);

static int semaphore_v(void);

static int sem_id;

int main(int argc, char *argv[])

{

int i;

int pause_time;

char op_char = ‘O’;

srand((unsigned int)getpid());

sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT);

if (argc > 1) {

if (!set_semvalue()) {

fprintf(stderr, “Failed to initialize semaphore\n”);

exit(EXIT_FAILURE);

}

op_char = ‘X’;

sleep(2);

}

2.   Then you have a loop that enters and leaves the critical section 10 times. There you first make a call to semaphore_p, which sets the semaphore to wait as this program is about to enter the critical section:

for(i = 0; i < 10; i++) {

if (!semaphore_p()) exit(EXIT_FAILURE);

printf(“%c”, op_char);fflush(stdout);

pause_time = rand() % 3;

sleep(pause_time);

printf(“%c”, op_char);fflush(stdout);

3.   After the critical section, you call semaphore_v, setting the semaphore as available, before going through the for loop again after a random wait. After the loop, the call to del_semvalue  is made to clean up the code:

if (!semaphore_v()) exit(EXIT_FAILURE);

pause_time = rand() % 2;

sleep(pause_time);

}

printf(“\n%d - finished\n”, getpid());

if (argc > 1) {

sleep(10);

del_semvalue();

}

exit(EXIT_SUCCESS);

}

4.   The function set_semvalue initializes the semaphore using the SETVAL command in a semctl  call. You need to do this before you can use the semaphore

static int set_semvalue(void)

{

union semun sem_union;

sem_union.val = 1;

if (semctl(sem_id, 0, SETVAL, sem_union) == -1) return(0);

return(1);

}

5.   The del_semvalue function has almost the same form, except that the call to semctl uses the command IPC_RMID to remove the semaphore’s ID:

static void del_semvalue(void)

{

union semun sem_union;

if (semctl(sem_id, 0, IPC_RMID, sem_union) == -1)

fprintf(stderr, “Failed to delete semaphore\n”);

}

6.   semaphore_p changes the semaphore by –1. This is the “wait” operation:

static int semaphore_p(void)

{

struct sembuf sem_b;

sem_b.sem_num = 0;

sem_b.sem_op = -1; /* P() */

sem_b.sem_flg = SEM_UNDO;

if (semop(sem_id, &sem_b, 1) == -1) {

fprintf(stderr, “semaphore_p failed\n”);

return(0);

}

return(1);

}

7.   semaphore_v is similar except for setting the sem_op part of the sembuf structure to 1. This is  the “release” operation, so that the semaphore becomes available:

static int semaphore_v(void)

{

struct sembuf sem_b;

sem_b.sem_num = 0;

sem_b.sem_op = 1; /* V() */

sem_b.sem_flg = SEM_UNDO;

if (semop(sem_id, &sem_b, 1) == -1) {

fprintf(stderr, “semaphore_v failed\n”);

return(0);

}

return(1);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值