C++中多线程
1.多線程
多線程案例:
#include <iostream>
#include <thread>
#include <string>
#include<windows.h>
?
using namespace std;
?
void run(int num)
{
??? Sleep(1000);
??? std::cout << "你好天朝" << num << endl;
}
?
void main()
{
??? thread *p[10];
??? for (int i = 0; i < 10;i++)
??? {
??????? p[i] = new thread(run,i);//循環創建線程
??????? //p[i]->join();//等待,相當于堵塞的狀態
??????? p[i]->detach();//脫離當前主線程自由執行,亂序,也就是說每個線程的執行是隨機的,是并發執行。
??? }
??? cin.get();
}
運行結果是:
2.線程案例2
#include <iostream>
#include <thread>
#include <string>
#include<windows.h>
?
using namespace std;
?
void helloworld()
{
??? std::cout << "你好天朝" << endl;
}
?
void helloworldA()
{
??? std::cout << "你好天朝A" << endl;
}
?
void helloworldB()
{
??? std::cout << "你好天朝B" << endl;
}
//通過下面這種方式實現的線程永遠是順序的
void main()
{
??? std::thread t1(helloworld);//線程順序執行
??? std::thread t2(helloworldA);
??? std::thread t3(helloworldB);
??? cin.get();
}
3.線程加鎖和線程解鎖
#include <iostream>
#include <thread>
#include <string>
#include<windows.h>
#include<mutex>
using namespace std;
//兩個線程并行訪問一個變量
int g_num = 20;//找到或者找不到的標識
mutex g_mutex;
void goA(int num)
{
??? //你訪問的變量,在你訪問期間,別人訪問不了,
??? //這種情況明顯可以看到自己被執行的次數多了
??? g_mutex.lock();
??? for (int i = 0; i < 15; i++)
??? {
??????? Sleep(300);
??????? g_num = 10;
??????? std::cout << "線程" << num << "?? " << g_num << endl;
??? }
??? g_mutex.unlock();
}
void goB(int num)
{
??? for (int i = 0; i < 15; i++)
??? {
??????? Sleep(500);
??????? g_num = 11;
??????? std::cout << "線程" << num << "?? " << g_num << endl;
??? }
}
void main()
{
??? thread t1(goA,1);
??? thread t2(goB, 2);
??? t1.join();
??? t2.join();
??? std::cin.get();
}
運行結果:
4.線程之間通信以及鎖定
案例:
#include <iostream>
#include <thread>
#include <string>
#include<windows.h>
?
using namespace std;
?
//兩個線程并行訪問一個變量
//找到或者找不到的標識
int g_num = 20;
?
void goA(int num)
{
??? for (int i = 0; i < 15;i++)
??? {
??????? Sleep(1000);
??????? if (i == 6)
??????? {
??????????? g_num = 5;
??????? }
??????? if (g_num == 5)
??????? {
??????????? std::cout << "線程" << num << "結束\n";
??????????? return;
??????? }
??????? std::cout << "線程" << num << "? " << g_num << endl;
??? }
}
?
void goB(int num)
{
??? for (int i = 0; i < 150; i++)
??? {
??????? Sleep(1000);
??????? if (g_num == 5)
??????? {
??????????? std::cout << "線程" << num << "結束?? \n";
??????????? return;
??????? }
??????? std::cout << "線程" << num << "?? " << g_num << endl;
??? }
}
?
void main()
{
??? thread t1(goA, 1);
??? thread t2(goB, 2);
??? t1.join();
??? t2.join();
?
??? std::cin.get();
}
?
總結