【发布时间】:2017-12-21 03:55:20
【问题描述】:
假设有 5 个线程在等待一个信号量
CreateSemaphore(sem_bridgempty,0,1,INFINITE);
WaitForSingleObject(sem_bridgempty, INFINITE);
现在,当 sem_bridgeempty 发出信号时,5 个线程中的一个将被唤醒,其余线程将再次等待 sem_bridgeempty 发出信号。我在这里吗?
我正在实施一个车道桥梁问题,一次只能有车辆从一个方向移动。桥梁的容量也固定为 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 方向行驶。现在有 3 个方向 2 的进入请求。所有 3 个都将在WaitForSingleObject(sem_bridgempty, INFINITE); 被阻止。现在当桥空了。三个中的一个将被接走。被选中的那个up 将再次使桥非空。即使方向相同,其他两个仍将等待桥空。
所以即使桥上有direction=2的车,其他同方向的车还在等sem_bridgempty。
我什至想过使用sem_bridgempty 作为事件而不是semaphore(setevent() 在cars_count=0 和resetevent() 在enter() 时resetevent() 当第一辆车进入时)。但仍然所有线程都不会唤醒起来。
【问题讨论】:
-
您不使用
std::condition_variable的任何特殊原因? -
没有特别的原因。但是我必须使用Windows同步功能来做到这一点,所以我想我可以尝试
sleepconditionvariablecs(),但是我也必须使用EnterCriticalSection()。这可以使用信号量来完成吗和互斥锁?我对这里的最佳方法感兴趣,即使我必须使用其他东西。 -
所选解决方案逻辑存在问题。你怎么看它不是最好的。试试this code
-
CreateSemaphore的参数不正确,丢弃返回值是不正确的,我希望你不要在每个线程中调用它。
标签: c++ windows multithreading visual-c++ semaphore