C++11新增了在之前版本中不曾有过的多线程机制,想想windows多线程编程那些晦涩的函数以及参数就头痛,现在不用担心了,C++标准库自带对多线程的支持,相信这是不少C++开发者听了就兴奋的事。
知识点 :thread mutex lock_guard sleep_for
本文通过简短的生产者和消费者模式运用C++11中多线程新增的功能。
#include<mutex>
//#include<condition_variable>
#include <iostream>
//#include<string>
#include<chrono>
#include<thread>
#include <stack>
using namespace std;
mutex mu;
stack<int> st{};
void PrintId(int id)
{
cout << "ID:" << id << endl;
}
void GetID()
{
while (true)
{
int id = 0;
if (st.size()>0)
{
std::lock_guard<std::mutex> lock(mu);
id = st.top();
st.pop();
PrintId(id);
}
else
{
cout << "ID:empty" << endl;
}
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
void PushId()
{
int id = 0;
while (true)
{
if (1)
{
std::lock_guard<std::mutex> lock(mu);
st.push(id);
}
id++;
std::this_thread::sleep_for(std::chrono::seconds(3));
}
}
int main()
{
thread tPush(PushId);
thread tGet(GetID);
tPush.detach();
tGet.detach();
getchar();
}