简体   繁体   English

通过信号量访问共享内存

[英]Get access to shared memory through semaphores

I have a different number of process which should write on the shared memory that I already defined. 我有不同数量的进程,应该在已经定义的共享内存上写入。 I'm trying by using system V semaphores. 我正在尝试使用系统V信号灯。 The semaphore ( sem_access ) is initialized at 1. 信号量( sem_access )初始化为1。

    sem_access.sem_op = -1;
    semop(sem_access_id, &sem_access, 1);

    info->index++;
    printf ("INDEX= %d\n", info->index);

    sem_access.sem_op = 1;
    semop(sem_access_id, &sem_access, 1);

The problem is that the printf prints always the same number, without increment the index. 问题是, printf总是打印相同的数字,而不会增加索引。 PS: Sorry for my bad english, but I'm spanish. PS:对不起,我的英语不好,但我是西班牙人。 edit: if I insert a sleep(1) it works well, but i really I don't want the sleep! 编辑:如果我插入sleep(1)效果很好,但是我真的不想睡觉!

provide some more info about your code. 提供有关您的代码的更多信息。 What problem you are getting ? 您遇到什么问题? Does your process get stuck once resources acquired or not waiting ? 一旦获得资源还是没有等待,您的流程是否会卡住?

man page of semop() says : semop()手册页说:

1) If sem_op is less than zero , the process must have alter permission on the semaphore set . 1)如果sem_op less than zero ,则该进程必须对semaphore set具有更改权限。 So if sem_access.sem_op = -1 ; 所以如果sem_access.sem_op = -1 ; when other process will make this value 0 or greater than 0 then only this process will access shared resources. 当其他进程将该值设为0或大于0时,则只有该进程将访问共享资源。

process 1 : sem_access.sem_op = -1; 进程1sem_access.sem_op = -1; //this process will wait until condition not true //此过程将等待直到条件不成立

process 2 : since in 1st process sem_op value is -1, this process needs to make sem_op value as 0 or 1 then only other process will get executed, So do like this 进程2 :由于在第一个进程中sem_op值为-1,因此此进程需要将sem_op值设为0或1,然后才执行其他进程,因此请执行以下操作

sem_access.sem_op = 1;

as man page of semop() says, If sem_op is a positive integer, the operation adds this value to the semaphore value (semval) . 如semop()的手册页所述,如果sem_op是一个正整数,则该操作this值添加到信号量值(semval) now sem_op becomes -1 + 1 = 0, refer again semop() man pages "This is a " wait-for-zero " operation: if semval is zero, the operation can immediately proceed". 现在sem_op变为-1 + 1 = 0,再次参考semop()手册页“这是一个“ wait-for-zero ”操作:如果semval为零,则该操作可以立即进行”。

I hope you got some idea to resolve problem. 希望您有解决问题的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM