64,637
社区成员
发帖
与我相关
我的任务
分享
#include <windows.h>
class CriticalSection
{
public:
CriticalSection() { ::InitializeCriticalSection(&m_cs); }
virtual ~CriticalSection() { ::DeleteCriticalSection(&m_cs); }
void Lock() { ::EnterCriticalSection(&m_cs); }
void Unlock() { ::LeaveCriticalSection(&m_cs); }
operator PCRITICAL_SECTION() { return &m_cs; }
protected:
CRITICAL_SECTION m_cs;
};
class Locker
{
public:
Locker(PCRITICAL_SECTION cs) : m_p(cs) { ::EnterCriticalSection(m_p); }
~Locker() { ::LeaveCriticalSection(m_p); }
protected:
PCRITICAL_SECTION m_p;
};
CriticalSection cs;
DWORD WINAPI Fun1Proc(LPVOID lpParameter // thread data
);
DWORD WINAPI Fun2Proc(LPVOID lpParameter // thread data
);
int index = 0;
int tickets = 100;
void main()
{
HANDLE hThread1, hThread2;
hThread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, Fun2Proc, NULL, 0, NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
/*while(index++ <100)
cout < <"main thread is runing" < <endl;*/
//Sleep(10);
Sleep(4000);
}
DWORD WINAPI Fun1Proc(LPVOID lpParameter // thread data
)
{
/*while(index++ <100)
cout < <"thread1 is runing" < <endl;*/
while (1)
{
Locker lock(cs);
if (tickets > 0) cout << "thread1 sell ticket:" << tickets-- << endl;
else break;
}
return 0;
}
DWORD WINAPI Fun2Proc(LPVOID lpParameter // thread data
)
{
while (1)
{
Locker lock(cs);
if (tickets > 0) cout << "thread2 sell ticket:" << tickets-- << endl;
else break;
}
return 0;
}
#include <iostream>
#include <string>
using namespace std;
#include <windows.h>
DWORD WINAPI Fun1Proc(LPVOID lpParameter // thread data
);
DWORD WINAPI Fun2Proc(LPVOID lpParameter // thread data
);
int index = 0;
int tickets = 100;
void main()
{
HANDLE hThread1, hThread2;
hThread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, Fun2Proc, NULL, 0, NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
/*while(index++ <100)
cout < <"main thread is runing" < <endl;*/
//Sleep(10);
Sleep(4000);
}
DWORD WINAPI Fun1Proc(LPVOID lpParameter // thread data
)
{
/*while(index++ <100)
cout < <"thread1 is runing" < <endl;*/
while (1)
{
if (tickets > 0) cout << "thread1 sell ticket:" << tickets-- << endl;
else break;
}
return 0;
}
DWORD WINAPI Fun2Proc(LPVOID lpParameter // thread data
)
{
while (1)
{
if (tickets > 0) cout << "thread2 sell ticket:" << tickets-- << endl;
else break;
}
return 0;
}