//#include <iostream>
//#include <windows.h>
//using namespace std;
//DWORD WINAPI Fun(LPVOID lpParamter)
//
//{
// while (1) { cout << "Fun display!\n"; Sleep(1000); }
//}
//
//
//int main()
//
//{
// HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
// CloseHandle(hThread);
// while (1) { cout << "main display!\n"; Sleep(2000); }
// return 0;
//}
#include <iostream>
#include <windows.h>
using namespace std;
HANDLE hMutex;
DWORD WINAPI Fun(LPVOID lpParamter)
{
while (1) {
WaitForSingleObject(hMutex, INFINITE);
cout << "Fun display!" << endl;
Sleep(1000);
ReleaseMutex(hMutex);
}
}
int main()
{
HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
hMutex = CreateMutex(NULL, FALSE, "screen");
CloseHandle(hThread);
while (1) {
WaitForSingleObject(hMutex, INFINITE);
cout << "main display!" << endl;
Sleep(2000);
ReleaseMutex(hMutex);
}
return 0;
}
//#include <windows.h>
//using namespace std;
//DWORD WINAPI Fun(LPVOID lpParamter)
//
//{
// while (1) { cout << "Fun display!\n"; Sleep(1000); }
//}
//
//
//int main()
//
//{
// HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
// CloseHandle(hThread);
// while (1) { cout << "main display!\n"; Sleep(2000); }
// return 0;
//}
#include <iostream>
#include <windows.h>
using namespace std;
HANDLE hMutex;
DWORD WINAPI Fun(LPVOID lpParamter)
{
while (1) {
WaitForSingleObject(hMutex, INFINITE);
cout << "Fun display!" << endl;
Sleep(1000);
ReleaseMutex(hMutex);
}
}
int main()
{
HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
hMutex = CreateMutex(NULL, FALSE, "screen");
CloseHandle(hThread);
while (1) {
WaitForSingleObject(hMutex, INFINITE);
cout << "main display!" << endl;
Sleep(2000);
ReleaseMutex(hMutex);
}
return 0;
}
本文介绍了一个使用C++和Windows API实现的多线程程序案例,通过互斥量(Mutex)来确保线程间对共享资源的安全访问。主函数创建了一个工作线程并初始化了一个互斥量,两个线程交替输出文本,展示了如何避免竞态条件。
300

被折叠的 条评论
为什么被折叠?



