操作系統 進程同步 實驗中 我們模擬了這一個小小的程序,如下:
#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的限制,看看在有限時間內這個互斥機制怎麼樣。但是,問題來了,我的電腦,在一千萬次的限制下,竟然**跑不出來**(跑了有幾十分鐘),後來我又跑到機房電腦上,仍是這樣。我試過很多數,一直到七百萬都可以,八百萬以後就不行了。可是這樣的運算量對計算機並不大啊,我很費解,得麻煩各路大神解釋一下了。
啊啊啊 各路大神 我明白了!! 我腦殘了 真的腦殘! 為撒要把倆線程綁到一個處理器上呢。。。綁到不同的處理器上就好了 我真的是腦殘。。。