prepare for c++17

This commit is contained in:
Changkun Ou
2018-03-26 09:08:36 +02:00
parent 8a3eb8f271
commit 71025d8bc6
39 changed files with 28 additions and 11 deletions

36
code/7/7.1.cpp Normal file
View File

@@ -0,0 +1,36 @@
//
// 7.1.cpp
// c++1x tutorial
//
// created by changkun at shiyanlou.com
//
// 线程支持库
#include <iostream>
#include <future>
#include <thread>
void foo() {
std::cout << "hello world" << std::endl;
}
void foo2() {
// 将一个返回值为7的 lambda 表达式封装到 task 中
// std::packaged_task 的模板参数为要封装函数的类型
std::packaged_task<int()> task([](){return 7;});
// 获得 task 的 future
std::future<int> result = task.get_future(); // 在一个线程中执行 task
std::thread(std::move(task)).detach(); std::cout << "Waiting...";
result.wait();
// 输出执行结果
std::cout << "Done!" << std:: endl << "Result is " << result.get() << '\n';
}
int main() {
std::thread t(foo);
foo2();
t.join();
return 0;
}

61
code/7/7.2.cpp Normal file
View File

@@ -0,0 +1,61 @@
//
// 7.2.cpp
// c++1x tutorial
//
// created by changkun at shiyanlou.com
//
// 生产者消费者模型
#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>
#include <queue>
#include <chrono>
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();
}