假设有5个线程等待信号多个线程等待同一个信号
CreateSemaphore(sem_bridgempty,0,1,INFINITE);
WaitForSingleObject(sem_bridgempty, INFINITE);
现在,当sem_bridgeempty发出信号,在5个线程的人会醒来,其余的将再次等待sem_bridgeempty
进行通知。我在这里吗?
我实现一个车道桥梁问题,其中可能存在的车辆只能在time.Also从一个方向移动的桥的容量是固定在5.什么到目前为止,我所做的是
unsigned WINAPI enter(void *param)
{
int direction = *((int *)param);
while (1)
{
WaitForSingleObject(sem_bridgecount, INFINITE);
WaitForSingleObject(mut_mutex, INFINITE);
if (curr_direction == -1 || direction == curr_direction)
{
curr_direction = direction;
cars_count++;
std::cout << "Car with direction " << direction << " entered " << GetCurrentThreadId() << std::endl;
ReleaseMutex(mut_mutex);
break;
}
else
{
ReleaseMutex(mut_mutex);
WaitForSingleObject(sem_bridgempty, INFINITE);
}
}
Sleep(5000);
exit1(NULL);
return 0;
}
unsigned WINAPI exit1(void *param)
{
WaitForSingleObject(mut_mutex, INFINITE);
cars_count--;
std::cout << "A Car exited " << GetCurrentThreadId() << std::endl;
ReleaseSemaphore(sem_bridgecount, 1, NULL);
if (cars_count == 0)
{
curr_direction = -1;
std::cout << "Bridge is empty " << GetCurrentThreadId() << std::endl;
ReleaseSemaphore(sem_bridgempty, 1, NULL);
}
ReleaseMutex(mut_mutex);
return 0;
}
int main()
{
sem_bridgecount = CreateSemaphore(NULL, 5, 5, NULL);
sem_bridgempty = CreateSemaphore(NULL, 0, 1, NULL);
mut_mutex = CreateMutex(NULL, false, NULL);
//create threads here
}
考虑下面的部分
else
{
ReleaseMutex(mut_mutex);
WaitForSingleObject(sem_bridgempty, INFINITE);
一辆车方向1.Now将会有三个输入与方向2.所有3将在WaitForSingleObject(sem_bridgempty, INFINITE);
。现在被封锁请求时,桥去的三empty.One会拿起来。拿起一个将再次使b即使方向相同,另外两个仍然会等待桥梁变空。 所以即使桥上有direction=2
汽车,其他方向相同的汽车仍在等待sem_bridgempty
。 我甚至(在exit1()
当cars_count=0
和resetevent()
在enter()
SetEvent的()当第一辆车进入)认为使用sem_bridgempty
作为一个事件,而不是semaphore
的。但仍然是所有线程不会醒来。
有什么特别的理由,你为什么不使用['的std :: condition_variable'(http://en.cppreference.com/ W/CPP /线程/ condition_variable)? – user0042
没有特别的原因。但是我必须使用windows同步函数来做这件事,所以我想我可以尝试'sleepconditionvariablecs()',但是我也必须使用'EnterCriticalSection()'。也可以使用信号量和互斥量来完成?即使我必须使用别的东西,我也对这里最好的方法感兴趣。 – user3819404
问题在选择的解决方案逻辑。你怎么看它不是最好的。尝试[此代码](https://stackoverflow.com/a/45133951/6401656) – RbMm