[英]C semaphores using sem_wait()
I am working with semaphores and I am struggling with one part of code. 我正在使用信号量,并且正在为代码的一部分而苦苦挣扎。
CODE: 码:
// semaphore initialized to zero
for( int i = 0; i < N; i++ )
{
fork();
// statements
sem_wait(semaphore);
printf("Process %d is done\n", i);
exit(0);
}
for( int i = 0; i < N; i++ )
{
sem_post(semaphore);
}
Problem is, that loop stops after first iteration because of sem_wait
, but i would like it to stop only that current process, so all other iterations can be done and at the end of code, i will 'release' all processes. 问题是,由于
sem_wait
,该循环在第一次迭代后停止,但是我希望它仅停止当前进程,因此可以完成所有其他迭代,并且在代码结束时,我将“释放”所有进程。 Is there a way how to accomplish this? 有没有办法做到这一点?
Thank you! 谢谢!
EDIT: 编辑:
// initialization of semaphore
semaphore = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
sem_init(semaphore, 1, 0);
Please check fork return value. 请检查fork返回值。 On that basis, you will be sure if code is executed under child or parent process.
在此基础上,您将确定代码是在子进程还是父进程下执行。 Accordingly call sem_wait.
因此调用sem_wait。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.