using namespace std;
DWORD increased = 0;
LONG atom_increase = 0;
LONG atom_stdout_inUse = 0;/* 控制输出的同步,否则可能会出现乱码 */
UINT IncreaseThread(LPVOID lpVoid)
{
DWORD* ThreadID = (DWORD*)lpVoid;
if
(ThreadID)
{
int count = 0;
while
(count++<3)
{
while
(::InterlockedExchange(&atom_increase, 1) == 1)
::Sleep(1);
/* 占用stdout */
while
(::InterlockedExchange(&atom_stdout_inUse, 1)==1)
{
::Sleep(1);
}
cout<<
"Thread "
<<*ThreadID<<
"\t"
<<increased++<<endl;
::InterlockedExchange(&atom_stdout_inUse, 0); /* 释放stdout */
::InterlockedExchange(&atom_increase, 0);
::Sleep(1);
}
/* 占用stdout */
while
(::InterlockedExchange(&atom_stdout_inUse, 1)==1)
{
::Sleep(1);
}
cout<<
"Thread "
<<*ThreadID<<
" quit"
<<endl;
::InterlockedExchange(&atom_stdout_inUse, 0); /* 释放stdout */
delete ThreadID;
return
0;
}
else
{
/* 占用stdout */
while
(::InterlockedExchange(&atom_stdout_inUse, 1)==1)
{
::Sleep(1);
}
cout<<
"invalid parameter!"
<<endl;
::InterlockedExchange(&atom_stdout_inUse, 0); /* 释放stdout */
return
1;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE handles[100];
DWORD nThreadCount = 64;
for
(int i = 0 ; i< nThreadCount; i++)
{
DWORD *Par = new DWORD;
*Par = i;
DWORD dwThreadID;
handles[i] = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)IncreaseThread,
Par, 0, &dwThreadID);
if
(handles[i] == NULL)
{
cout<<
"create thread failed"
<<i<<endl;
}
}
::WaitForMultipleObjects(nThreadCount, handles, TRUE, INFINITE);
for
(i=0; i<nThreadCount; i++)
{
CloseHandle(handles[i]);
}
cout<<
"leave"
<<endl;
return
0;
}