我在C中的信号量存在很大问题.这是我的代码灵感的链接:http://cse.unl.edu/~ylu/csce351/notes/Solution%20for%20Building%20H2O.pdf.
氢和氧有两个相似的代码.这是一个想法:有氧气和氢气生成的过程,它们是在不同的时间产生的.当有2个氢和1个氧时,它们起作用bond().但他们必须等待他们.在将条件评估为false之后,应该切换到另一个进程(或者至少这是我理解它的方式).但是在我的代码中,它继续执行下一个命令,导致它不会等待我需要的所有进程.它会在创建的每个进程之后打印到输出,即使它应该等待.有谁知道那里有什么不对吗?
(如果这还不够,我可以发布更多的代码.)
氧代码:(氢气相似)
sem_wait(mutex);
if ((*hydrogen >=2) && (*oxigen>=1))
{
(*count_c)++;
*count_cur_h-=2;
sem_post(hydrel);
sem_post(hydrel);
*count_cur_o-=1;
sem_post(oxrel);
}
else
{
(*count_c)++;
sem_post(mutex); // This is the place where it is supposed
// to release and continue to another process,
// but it goes to the next command.
}
sem_wait(oxrel);
bond();
sem_wait(barrier);
//semaphores are initialized like this:
sem_init(mutex,1,1);
sem_init(oxrel,1,1);
sem_init(hydrel,1,2);
sem_init(barrier,1,3);
Run Code Online (Sandbox Code Playgroud)
sem_post 不是阻塞调用。sem_wait 是阻塞调用。如果调用 sem_wait 时信号量的值为零,则调用它的函数将阻塞。sem_post 用于在信号量值为零时释放另一个正在阻塞等待 sem_wait 的线程,但它本身不会阻塞。sem_post 调用用于“唤醒等待 sem-wait 的线程”,然后继续向前,然后两个线程将同时运行(如果您至少有 2 个逻辑 CPU)。如果您希望调用 sem_post 的线程在此时阻塞,您将需要执行其他操作(例如添加另一个信号量)。