gpt4 book ai didi

c++ - 如何使用互斥使两个线程严格交替?

转载 作者:太空狗 更新时间:2023-10-29 19:46:43 26 4
gpt4 key购买 nike

我需要创建两个严格交替的线程。这是我使用的示例代码:

#include <Windows.h>
#include <iostream>
using std::cout;
using std::endl;

HANDLE g_hMutex1;
HANDLE g_hMutex2;

DWORD WINAPI ThreadFunc1(LPVOID lpParam);
DWORD WINAPI ThreadFunc2(LPVOID lpParam);

int main(void)
{
int nCalcNumber = 10;
DWORD dwThreadId;
HANDLE pThreadHandles[2];

g_hMutex1 = CreateMutex(NULL, FALSE, NULL);
g_hMutex1 = CreateMutex(NULL, FALSE, NULL);

pThreadHandles[0] = CreateThread(
NULL,
0,
ThreadFunc1,
static_cast<void*>(&nCalcNumber),
0,
&dwThreadId);

pThreadHandles[1] = CreateThread(
NULL,
0,
ThreadFunc2,
static_cast<void*>(&nCalcNumber),
0,
&dwThreadId);

WaitForMultipleObjects(2, pThreadHandles, TRUE, INFINITE);

CloseHandle(pThreadHandles[0]);
CloseHandle(pThreadHandles[1]);
CloseHandle(g_hMutex1);
CloseHandle(g_hMutex2);

return 0;
}

DWORD WINAPI ThreadFunc1(LPVOID lpParam)
{
int* nCalcNumber = static_cast<int*>(lpParam);

for (int i = 0; i < *nCalcNumber; i++)
{
WaitForSingleObject(g_hMutex1, INFINITE);

cout << "Func 1" << endl;

ReleaseMutex(g_hMutex1);
}

return 0;
}

DWORD WINAPI ThreadFunc2(LPVOID lpParam)
{
int* nCalcNumber = static_cast<int*>(lpParam);

for (int i = 0; i < *nCalcNumber; i++)
{
WaitForSingleObject(g_hMutex1, INFINITE);

cout << "Func 2" << endl;

ReleaseMutex(g_hMutex1);
}

return 0;
}

以及我希望收到的结果:

 Func 1
Func 2
Func 1
Func 2
Func 1
Func 2
...and so one

应该添加什么以获得期望的结果。我可以为此使用第二个互斥体吗?

最佳答案

如其他答案所述,信号量是比互斥量更好的选择。但作为一个纯粹的学术练习(家庭作业?),您也可以使用互斥锁来完成。 (强调:这是一个纯粹的学术练习。真正的程序不应该使用这种技术。)

DWORD WINAPI ThreadFunc1(LPVOID lpParam)
{
int* nCalcNumber = static_cast<int*>(lpParam);

WaitForSingleObject(g_hMutex2, INFINITE);
for (int i = 0; i < *nCalcNumber; i++)
{
WaitForSingleObject(g_hMutex1, INFINITE);
ReleaseMutex(g_hMutex2);

cout << "Func 1" << endl;

ReleaseMutex(g_hMutex1);
WaitForSingleObject(g_hMutex2, INFINITE);
}

return 0;
}

DWORD WINAPI ThreadFunc2(LPVOID lpParam)
{
int* nCalcNumber = static_cast<int*>(lpParam);

WaitForSingleObject(g_hMutex2, INFINITE);
for (int i = 0; i < *nCalcNumber; i++)
{
WaitForSingleObject(g_hMutex1, INFINITE);
ReleaseMutex(g_hMutex2);

cout << "Func 2" << endl;

ReleaseMutex(g_hMutex1);
WaitForSingleObject(g_hMutex2, INFINITE);
}

return 0;
}

Mutex 1 是“我有它”互斥锁,Mutex 2 是“我想要它下一个”互斥锁。

关于c++ - 如何使用互斥使两个线程严格交替?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7943974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com