65,187
社区成员




#include <iostream>
#include <process.h>
#include <Windows.h>
using namespace std;
long total = 0;
const int M = 100000;
unsigned __stdcall ThreadProc(void*)
{
for(long i = 1; i <= M; i++)
total += 1;
return 0;
}
int main(int argc, char* argv[])
{
const int N = 10000;
HANDLE h[2];
int min = 0;
int max = 0;
//统计N次total的最小和最大值
for(int i = 0; i < N; i++)
{
total = 0;
h[0] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, NULL, 0, NULL);
h[1] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, NULL, 0, NULL);
//等待两个线程都结束
WaitForMultipleObjects(2, h, TRUE, INFINITE);
CloseHandle(h[0]);
CloseHandle(h[1]);
if(min == 0)
min = total;
if(total < min)
{
min = total;
}
if(total > max)
{
max = total;
}
}
cout << "(" << min << "," << max << ")";
return 0;
}
1, mov eax,dword ptr [total (0E69148h)]
2, add eax,1
3, mov dword ptr [total (0E69148h)],eax
ThreadProc proc near
add total, 186A0h
xor eax, eax
retn 4
ThreadProc endp
h[0] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, NULL, CREATE_SUSPENDED, NULL);
h[1] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, NULL, CREATE_SUSPENDED, NULL);
SetThreadAffinityMask(h[0], 2);
SetThreadAffinityMask(h[1], 4);
::ResumeThread(h[0]);
::ResumeThread(h[1]);
h[0] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, NULL, 0, NULL);
h[1] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, NULL, 0, NULL);
这两行代码是向操作系统申请开启两个线程,系统什么时候开启两个线程则不是确定的。不能假定两个线程一定是同时开启,所以全局变量的值是随机的。