#include
#include
using namespace std;
int index = 0;
// 临界区结构对象
CRITICAL_SECTION g_cs;
HANDLE hMutex = NULL;
void changeMe()
{
cout << index++ << endl;
}
void changeMe2()
{
cout << index++ << endl;
}
void changeMe3()
{
cout << index++ << endl;
}
DWORD WINAPI th1(LPVOID lpParameter)
{
while(1)
{
Sleep(1600); //sleep 1.6 s
// 进入临界区
EnterCriticalSection(&g_cs);
// 等待互斥对象通知
//WaitForSingleObject(hMutex, INFINITE);
// 对共享资源进行写入操作
//cout << "a" << index++ << endl;
changeMe();
changeMe2();
changeMe3();
// 释放互斥对象
//ReleaseMutex(hMutex);
// 离开临界区
LeaveCriticalSection(&g_cs);
}
return 0;
}
DWORD WINAPI th2(LPVOID lpParameter)
{
while(1)
{
Sleep(2000); //sleep 2 s
// 进入临界区
EnterCriticalSection(&g_cs);
// 等待互斥对象通知
//WaitForSingleObject(hMutex, INFINITE);
//cout << "b" << index++ << endl;
changeMe();
changeMe2();
changeMe3();
// 释放互斥对象
//ReleaseMutex(hMutex);
// 离开临界区
LeaveCriticalSection(&g_cs);
}
return 0;
}
int main(int argc, char* argv[])
{
// 创建互斥对象
//hMutex = CreateMutex(NULL, TRUE, NULL);
// 初始化临界区
InitializeCriticalSection(&g_cs);
HANDLE hThread1;
HANDLE hThread2;
hThread1 = CreateThread(NULL, 0, th1, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, th2, NULL, 0, NULL);
int k;
cin >> k;
printf("Hello World!\n");
return 0;
}
阅读(13917) | 评论(1) | 转发(0) |