题目:
#include <iostream>
#include <windows.h>
#include <tchar.h>
// 我想使用线程,让线程按我制定?的方案执行,但是总失败
// 起床-》吃饭-》工作 -》回家 -》起床
HANDLE mutext1;
HANDLE mutext2;
HANDLE mutext3;
HANDLE mutext4;
DWORD CALLBACK Step1(void* param) {
while (1) {
WaitForSingleObject(mutext1, -1);
printf("起床/n");
ReleaseMutex(mutext2);
}
return 0;
}
DWORD CALLBACK Step2(void* param) {
while (1) {
WaitForSingleObject(mutext2, -1);
printf("吃饭/n");
ReleaseMutex(mutext3);
}
return 0;
}
DWORD CALLBACK Step3(void* param) {
while (1) {
WaitForSingleObject(mutext3, -1);
printf("工作/n");
ReleaseMutex(mutext3);
}
return 0;
}
DWORD CALLBACK Step4(void* param) {
while (1) {
WaitForSingleObject(mutext4, -1);
printf("回家/n");
ReleaseMutex(mutext1);
}
return 0;
}
int main() {
mutext1 = CreateMutexW(NULL, FALSE, NULL);
mutext2 = CreateMutexW(NULL, FALSE, NULL);
mutext3 = CreateMutexW(NULL, FALSE, NULL);
mutext4 = CreateMutexW(NULL, FALSE, NULL);
CreateThread(NULL, NULL, Step1, NULL, NULL, NULL);
CreateThread(NULL, NULL, Step2, NULL, NULL, NULL);
CreateThread(NULL, NULL, Step3, NULL, NULL, NULL);
CreateThread(NULL, NULL, Step4, NULL, NULL, NULL);
Sleep(50000);
return 0;
}
错误原因:互斥体只能在自己线程解锁。
解决方案不唯一,用事件也可以实现。
这里还是改互斥体的错误。
#include <iostream>
#include <windows.h>
#include <tchar.h>
// 我想使用线程,让线程按我制定?的方案执行,但是总失败
// 起床-》吃饭-》工作 -》回家 -》起床
HANDLE mutext1;
int step = 0;
// 错误原因:互斥体只能在自己线程中解锁,其他线程解锁无效
DWORD CALLBACK Step1(void* param) {
while (1) {
WaitForSingleObject(mutext1, -1); // 等待激发态,并设置为非激发态
if (step % 4 == 0) {
step++;
printf("起床/n");
Sleep(500);
}
ReleaseMutex(mutext1);
}
return 0;
}
DWORD CALLBACK Step2(void* param) {
while (1) {
WaitForSingleObject(mutext1, -1);
if (step % 4 == 1) {
step++;
printf("吃饭/n");
Sleep(500);
}
ReleaseMutex(mutext1);
}
return 0;
}
DWORD CALLBACK Step3(void* param) {
while (1) {
WaitForSingleObject(mutext1, -1);
if (step % 4 == 2) {
step++;
printf("工作/n");
Sleep(500);
}
ReleaseMutex(mutext1);
}
return 0;
}
DWORD CALLBACK Step4(void* param) {
while (1) {
WaitForSingleObject(mutext1, -1);
if (step % 4 == 3) {
step++;
printf("回家/n/n");
Sleep(500);
}
ReleaseMutex(mutext1);
}
return 0;
}
int main() {
mutext1 = CreateMutexW(NULL, FALSE, NULL);
//mutext2 = CreateMutexW(NULL, FALSE, NULL);
//mutext3 = CreateMutexW(NULL, FALSE, NULL);
//mutext4 = CreateMutexW(NULL, FALSE, NULL);
CreateThread(NULL, NULL, Step1, NULL, NULL, NULL);
CreateThread(NULL, NULL, Step2, NULL, NULL, NULL);
CreateThread(NULL, NULL, Step3, NULL, NULL, NULL);
CreateThread(NULL, NULL, Step4, NULL, NULL, NULL);
Sleep(50000);
return 0;
}
当然要注意的地方,step++ 还没做完,线程立即崩溃,一样还是会有死锁问题,不过不属于题目了。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/282844.html