[英]Semaphores failing to wait, with reason “Resource temporarily unavailable”
我正在嘗試讓父進程在父進程繼續之前等待多個子進程信號,使用一組未命名的信號量(每個子進程一個)。 但是,當使用sem_wait()時,父進程無限期地等待,而sem_trywait()返回“資源暫時不可用”錯誤,並且在子進程沒有發出信號的情況下繼續。 sem_init()和sem_post()都不會返回錯誤。
相關部分代碼:
int numsems = concurrent_instrs.size();
std::cout << "Num sems: " << numsems << "\n";
// create semaphores
sem_t* sems = new sem_t[numsems];
for (int i = 0; i < numsems; i++)
{
if (sem_init(&sems[i], 1, 0) < 0)
{
perror("sem initialization failed");
exit(1);
}
}
int child_num = 0;
// perform all calculations in block concurrently
for(unsigned int i = 0; i < concurrent_instrs.size() && !isChild; i++)
{
int pid = fork();
if (pid == -1)
{
perror("Error forking:");
exit(1);
}
if (pid == 0)
{
isChild = true;
instr = concurrent_instrs[i];
}
else
{
child_num++;
}
}
if (isChild)
{
std::cout << "Child process " << child_num << " calculating: " << instr << "\n";
perform_calculation(instr, input_vars, internal_vars, shm_input, shm_internal);
std::cout << "Child process " << child_num << " finished calculating\n";
if (sem_post(&sems[child_num]) < 0)
{
perror("Child signal failed");
}
std::cout << "Child "<< child_num << " signalled\n";
// detach from shared memory
if (shmdt(shm_input) < 0)
{
perror("child shm_input detach failed");
}
if (shmdt(shm_internal) < 0)
{
perror("child shm_internal detach failed");
}
exit(0);
}
else
{
// parent waits for all children to finish
for (int i = 0; i < numsems; i++)
{
std::cout << "Waiting on subprocess " << i << " of " << numsems << "\n";
if (sem_trywait(&sems[i]) < 0)
perror("Parent wait failed");
else
std::cout << "Parent wait " << i << " working\n";
}
std::cout << "Finished waiting\n";
// destroy semaphores
for (int i = 0; i < numsems; i++)
{
if(sem_destroy(&sems[i]) < 0)
{
perror("Sem destroy failed");
exit(2);
}
else
{
std::cout << "Sem " << i << " destroyed\n";
}
}
delete[] sems;
}
我是否設置錯誤,或者只是誤解了如何在這種情況下使用信號量?
編輯添加:sem_wait()遇到錯誤,無論子進程在等待之前或之后調用sem_post()。
用sem_t* sems = new sem_t[numsems];
分配的信號量sem_t* sems = new sem_t[numsems];
不在共享內存中。 因此,每個進程都有自己的副本,並且在子進程中發布不會影響父進程。
父母的副本保持鎖定狀態。 sem_trywait
因EAGAIN
而失敗,這轉換為resource temporarily unavailable
解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.