C++在11版之前貌似是沒有線程功能的。
終於在C++11將線程加入進來了,喜大普奔。
C++11引入了thread類,大大降低多線程使用複雜度,一套代碼平臺移植,現在C++11中只需使用語言層面的thread可以解決這個問題。
今天介紹一哈C++11的線程如何運用哦。這裏我使用的是Vs2015。
線程頭文件
#include < thread > // 引入線程
#include < mutex > // 引入線程鎖
線程聲明
std::thread testThread( zzz, x, y, …);
zzz爲線程所執行的函數。
x、y等均爲傳入參數
testThread.join(); // 阻塞方式運行
testThread.detach(); // 非阻塞方式運行
testThread.get_id(); // 線程id,std::cout << testThread.get_id();
線程鎖
mutex Mutex;
Mutex.lock(); //加鎖
Mutex.unlock(); //解鎖
std::ref和std::cref (與線程無關)
std::ref 用於包裝按引用傳遞的值。
std::cref 用於包裝按const引用傳遞的值。
線程睡眠
this_thread::sleep_for(chrono::minutes(1)); // 睡眠1分鐘
this_thread::sleep_for(chrono::seconds(1)); // 睡眠1秒
this_thread::sleep_for(chrono::milliseconds(100)); // 睡眠100毫秒
this_thread::sleep_for(chrono::microseconds(100)); // 睡眠100微秒
賣票例子
1、創建買票類對象
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
class ThreadTest
{
public:
//賣票線程1
void ThreadTest::Thread1(unsigned short);
//賣票線程2
void ThreadTest::Thread2(char *);
ThreadTest();
private:
//票的剩餘數目
int Sum;
mutex Mutex;//線程鎖
};
2、實現賣票類
#include "ThreadTest.h"
void ThreadTest::Thread1(unsigned short value)
{
for (;;)
{
Mutex.lock(); // 加鎖
--Sum;
if (Sum < 0)
{
printf("Thrad1——票賣完了\n", Sum);
Mutex.unlock(); // 解鎖
break;
}
printf("Thrad1——剩餘票數:%d\t%d\n", Sum, value);
Mutex.unlock(); // 解鎖
this_thread::sleep_for(chrono::milliseconds(10)); // 休息
}
}
void ThreadTest::Thread2(char *buf)
{
for (;;)
{
Mutex.lock(); // 加鎖
--Sum;
if (Sum < 0)
{
printf("Thrad2——票賣完了\n");
Mutex.unlock(); // 解鎖
break;
}
printf("Thrad2——剩餘票數:%d\t%s\n", Sum,buf);
Mutex.unlock(); // 解鎖
this_thread::sleep_for(chrono::milliseconds(100)); // 休息
}
}
//構造函數
ThreadTest::ThreadTest()
{
Sum = 200;
unsigned short Thread1 = 100;
thread t1(&ThreadTest::Thread1, this, std::ref(Thread1));
std::cout << "線程t1的id:" << t1.get_id() << std::endl;
t1.detach();
char *buf = new char[1024];
memset(buf, 0, 1024);
memcpy(buf, "hello,world!\0", 12);
thread t2(&ThreadTest::Thread2, this, buf);
std::cout << "線程t2的id:" << t2.get_id() << std::endl;
t2.join();
delete buf;
buf = nullptr;
}
3、調用
#include "ThreadTest.h"
int main()
{
//多線程賣票類
ThreadTest SaleThread;
system("pause");
return 0;
}
結果
源碼
正在上傳源碼,稍候。
關注
微信公衆號搜索"Qt_io_"或"Qt開發者中心"瞭解更多關於Qt、C++開發知識.。
筆者 - jxd