操作系统 进程同步 实验中 我们模拟了这一个小小的程序,如下:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int c1 = 0;
int c2 = 0;
int will_wait;
int accnt1 = 0;
int accnt2 = 0;
DWORD WINAPI run1( LPVOID p ) {
unsigned long counter = 0;
int tmp1, tmp2, r;
int flag = 1;
DWORD start, end;
start = GetTickCount();
while(flag) {
c1 = 1;
will_wait = 1;
while(c2 && (will_wait == 1));
// wait loop
r = rand();
tmp1 = accnt1;
tmp2 = accnt2;
accnt1 = tmp1 + r;
accnt2 = tmp2 - r;
counter++;
if (counter >= 10000000 || accnt1 + accnt2 != 0)
flag = 0;
c1 = 0;
}
end = GetTickCount();
printf("Thread %lu:\n", GetCurrentThreadId());
printf("counter = %lu, execution time = %lu ms\n", counter, (end - start));
return 0;
}
DWORD WINAPI run2( LPVOID p ) {
unsigned long counter = 0;
int tmp1, tmp2, r;
int flag = 1;
DWORD start, end;
start = GetTickCount();
while(flag) {
c2 = 1;
will_wait = 2;
while(c1 && (will_wait == 2));
// wait loop
r = rand();
tmp1 = accnt1;
tmp2 = accnt2;
accnt1 = tmp1 + r;
accnt2 = tmp2 - r;
counter++;
if (counter >= 10000000 || accnt1 + accnt2 != 0)
flag = 0;
c2 = 0;
}
end = GetTickCount();
printf("Thread %lu:\n", GetCurrentThreadId());
printf("counter = %lu, execution time = %lu ms\n", counter, (end - start));
return 0;
}
int main() {
HANDLE hFirst = CreateThread(NULL, 0, run1, NULL, 0, NULL);
HANDLE hSecond = CreateThread(NULL, 0, run2, NULL, 0, NULL);
// CPU affinity
SetThreadAffinityMask(hFirst, 1);
SetThreadAffinityMask(hSecond, 1);
// INFINITE
WaitForSingleObject(hFirst, INFINITE);
WaitForSingleObject(hSecond, INFINITE);
system("PAUSE");
return 0;
}
这是软件方法去使两个线程程互斥(我已经把两个线程全绑定到了一个固定的CPU线程上去)。从代码中可以看到,如果没有counter的限制,理想情况应该是两个线程一直跑下去。但我想通过counter的限制,看看在有限时间内这个互斥机制怎么样。但是,问题来了,我的电脑,在一千万次的限制下,竟然**跑不出来**(跑了有几十分钟),后来我又跑到机房电脑上,仍是这样。我试过很多数,一直到七百万都可以,八百万以后就不行了。可是这样的运算量对计算机并不大啊,我很费解,得麻烦各路大神解释一下了。