本文主要是介绍C++11单/多线程总结(三十五),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.代码示例
#include <iostream>
#include <thread>
#include <mutex>
#include <future>
#include <condition_variable>
#include <queue>
#include <chrono>//1.thread usage demo
#if 0
void foo(){std::cout << "hello" << std::endl;
}int main(){std::thread t(foo);t.join();return 0;
}#endif//2.mutex usage demo
#if 0
std::mutex mtx;void block_area(){std::unique_lock<std::mutex> lock(mtx);//...临界区
}int main(){std::thread thd1(block_area);thd1.join();return 0;
}#endif#if 0
//3.thread Asynchrony operation
int main()
{//将一个返回值为7的 lambda 表达式封装到 task 中//std::packaged_task 的模板参数为要封装函数的类型std::packaged_task<int()> task([](){return 7;});//获得 task 的 futurestd::future<int> result = task.get_future(); // 在一个线程中执行 taskstd::thread(std::move(task)).detach(); std::cout << "Waiting...";result.wait();//输出执行结果std::cout << "Done!" << std:: endl << "Result is " << result.get() << '\n';
}#endif//4.producer and consumer model demo.
#if 1
int main()
{// 生产者数量std::queue<int> produced_nums;// 互斥锁std::mutex m;// 条件变量std::condition_variable cond_var;// 结束标志bool done = false;// 通知标志bool notified = false;// 生产者线程std::thread producer([&]() {for (int i = 0; i < 5; ++i) {std::this_thread::sleep_for(std::chrono::seconds(1));// 创建互斥锁std::unique_lock<std::mutex> lock(m);std::cout << "producing " << i << '\n';produced_nums.push(i);notified = true;// 通知一个线程cond_var.notify_one();}done = true;cond_var.notify_one();});// 消费者线程std::thread consumer([&]() {std::unique_lock<std::mutex> lock(m);while (!done) {while (!notified) { // 循环避免虚假唤醒cond_var.wait(lock);}while (!produced_nums.empty()) {std::cout << "consuming " << produced_nums.front() << '\n';produced_nums.pop();}notified = false;}});producer.join();consumer.join();
}
#endif
这篇关于C++11单/多线程总结(三十五)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!