测试多线程。
方案一:
#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会智能分配时间片吧
有时候,还会出现这个问题:
实在搞不懂这个多线程的运作方式。