測試多線程。
方案一:
#include <Windows.h> // 使用多線程,要加頭文件
#include <iostream>
using namespace std;
int a = 1;
CRITICAL_SECTION g_cs; // 線程鎖
// 開闢兩個線程,分別對同一個變量進行操作
DWORD WINAPI thread1(LPVOID lpParameter)
{
while(true)
{
EnterCriticalSection(&g_cs);
if (a < 50)
{
//Sleep(1);
cout << "thread1: a = " << a++ << endl;
}
else
break;
LeaveCriticalSection(&g_cs);
}
return 0;
}
DWORD WINAPI thread2(LPVOID lpParameter)
{
while(true)
{
EnterCriticalSection(&g_cs);
if (a < 50)
{
//Sleep(1);
cout << "thread2: a = " << a++ << endl;
}
else
break;
LeaveCriticalSection(&g_cs);
}
return 0;
}
int main()
{
InitializeCriticalSection(&g_cs);
HANDLE ht_1, ht_2;
ht_1 = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
ht_2 = CreateThread(NULL, 0, thread2, NULL, 0, NULL);
CloseHandle(ht_1);
CloseHandle(ht_2);
Sleep(300);
cout << "main thread" << endl;
DeleteCriticalSection(&g_cs);
system("pause");
return 0;
}
運行結果: 很奇怪,只有1線程在運行。分析原因:可能是因爲系統自動分配時間片的時候,過大,導致1線程一直在執行。
方案二:
將上面的Sleep(1) 去掉註釋, 當每個函數進入自己的裏面時,先把控制權交出去,看看是不是會交錯輸出。
輸出結果同上,還是隻有1線程輸出。 難道是電腦CPU的原因? 我的CPU:
方案三: 用兩個鎖,互不干擾。
#include <Windows.h> // 使用多線程,要加頭文件
#include <iostream>
using namespace std;
int a = 1;
CRITICAL_SECTION g_cs1, g_cs2; // 線程鎖
// 開闢兩個線程,分別對同一個變量進行操作
DWORD WINAPI thread1(LPVOID lpParameter)
{
while(true)
{
EnterCriticalSection(&g_cs1);
if (a < 50)
{
//Sleep(1);
cout << "thread1: a = " << a++ << endl;
}
else
break;
LeaveCriticalSection(&g_cs1);
}
return 0;
}
DWORD WINAPI thread2(LPVOID lpParameter)
{
while(true)
{
EnterCriticalSection(&g_cs2);
if (a < 50)
{
//Sleep(1);
cout << "thread2: a = " << a++ << endl;
}
else
break;
LeaveCriticalSection(&g_cs2);
}
return 0;
}
int main()
{
InitializeCriticalSection(&g_cs1);
InitializeCriticalSection(&g_cs2);
HANDLE ht_1, ht_2;
ht_1 = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
ht_2 = CreateThread(NULL, 0, thread2, NULL, 0, NULL);
CloseHandle(ht_1);
CloseHandle(ht_2);
Sleep(300);
cout << "main thread" << endl;
DeleteCriticalSection(&g_cs1);
DeleteCriticalSection(&g_cs2);
system("pause");
return 0;
}
運行結果:交替的挺好。 偶爾又不太行。可能是CPU會智能分配時間片吧
有時候,還會出現這個問題:
實在搞不懂這個多線程的運作方式。