餐饮哲学家问题 - 只有 2 个线程工作
Dining philosophers problem - only 2 thread worked
我正在尝试解决餐饮哲学家的问题。
就我而言,每个哲学家都应该吃100万次。 问题是它似乎只有"1"并且"3"吃完了。 我正在使用具有关键部分锁定的线程,这是我的代码:
CRITICAL_SECTION ghCARITICALSection1;
CRITICAL_SECTION ghCARITICALSection2;
CRITICAL_SECTION ghCARITICALSection3;
CRITICAL_SECTION ghCARITICALSection4;
CRITICAL_SECTION ghCARITICALSection5;
DWORD WINAPI func(int* phiphilosopher)
{
if (1 == *phiphilosopher && TryEnterCriticalSection(&ghCARITICALSection1) && TryEnterCriticalSection(&ghCARITICALSection2))
{
std::cout << "1 is eating...n";
for (int i = 0; i < 1000000; i++)
{
i = i;
}
LeaveCriticalSection(&ghCARITICALSection1);
LeaveCriticalSection(&ghCARITICALSection2);
}
if (2 == *phiphilosopher && TryEnterCriticalSection(&ghCARITICALSection2) && TryEnterCriticalSection(&ghCARITICALSection3))
{
std::cout << "2 is eating...n";
for (int i = 0; i < 1000000; i++)
{
}
LeaveCriticalSection(&ghCARITICALSection2);
LeaveCriticalSection(&ghCARITICALSection3);
}
if (3 == *phiphilosopher && TryEnterCriticalSection(&ghCARITICALSection3) && TryEnterCriticalSection(&ghCARITICALSection4))
{
std::cout << "3 is eating...n";
for (int i = 0; i < 1000000; i++)
{
}
LeaveCriticalSection(&ghCARITICALSection3);
LeaveCriticalSection(&ghCARITICALSection4);
}
//...also for 4,5
return 0;
}
int philosopher1 = 1;
int* philosopher1ptr = &philosopher1;
int philosopher2 = 2;
int* philosopher2ptr = &philosopher2;
//...Also for philosopher 3,4,5
InitializeCriticalSection(&ghCARITICALSection1);
InitializeCriticalSection(&ghCARITICALSection2);
//...aslo for ghCARITICALSection 3,4,5
HANDLE WINAPI th1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, philosopher1ptr, 0, NULL);
HANDLE WINAPI th2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, philosopher2ptr, 0, NULL);
////...aslo for th3,4,5
WaitForSingleObject(th1, INFINITE);
WaitForSingleObject(th2, INFINITE);
//...also for th3,4,5
- 每个哲学家都必须交替思考和吃饭。然而,哲学家只有在左右叉子都有时才能吃意大利面。每个叉子只能由一个哲学家握住,因此一个哲学家只有在另一个哲学家不使用叉子的情况下才能使用叉子。
想想这里的逻辑
if (TryEnterCriticalSection(&a) && TryEnterCriticalSection(&b)) {
// . . .
LeaveCriticalSection(&a);
LeaveCriticalSection(&b);
}
如果TryEnterCriticalSection(&a)
成功而TryEnterCriticalSection(&b)
失败会发生什么;CSa
永远处于进入状态。
它应该看起来像
if (TryEnterCriticalSection(&a)) {
if (TryEnterCriticalSection(&b)) {
// . . .
LeaveCriticalSection(&b);
}
LeaveCriticalSection(&a);
}
相关文章:
- C++为线程工作动态地分割例程
- 自 Windows 10 20H1 以来,具有单独线程的多个窗口停止工作
- 餐饮哲学家问题 - 只有 2 个线程工作
- 工作线程在执行太快后永久休眠
- 唤醒多个线程以在每个条件下工作一次
- Qt::D irectConnection在多线程环境中使用时如何工作?
- ZeroMQ 在使用 std::thread 创建工作线程时崩溃
- 工作线程一直在等待,condition_variable甚至调用了notify_all
- 使用 std::atomic 标志和 std::condition_variable 在工作线程上等待
- SIGABRT 和线程相关的异常,但在调试期间工作正常
- c++线程的安全性和时间效率:为什么有互斥检查的线程有时比没有它的线程工作得更快
- 在多线程工作负载上解释Gperftools的结果
- 我的线程工作不好,它给出了所有结果,最后没有一个接一个,GUI 在线程运行期间挂起?
- BOOST::线程工作线程同步,C++和OpenCV
- 线程工作不正常
- 提升线程工作线程对象在线程完成后的重用
- 线程问题,其中一个线程工作,但导致调用方法不返回
- 线程工作目录
- MFC主UI线程工作和模态对话框
- 用类对象提升线程工作器