c++ 异步并行编程

Cplusplus
回复
ccc
初来炸道
初来炸道
帖子: 7
注册时间: 2016年09月18日 21:50
联系:

c++ 异步并行编程

帖子 ccc »

主要头文件:future
学习 future 编程的前提是会了 std::condition_variable,否则对 std::future 系之 wait, set_*,get 的理解有障碍。
1. std::async
创建一个异步 future, 第一个参数设置策略,可以是
std::launch::async 异步策略:自动并行;
std::launch::deferred 延迟策略:只有使用 std::future 的 wait, get 方法才会触发执行;
2. std::packaged_task
包裹一个执行序,它是一个 moveable 类型的线程执行序,可以用 get_future 方法获得 future
3. std::promise
良好的 set/get 封装,实现 promise/future 并行化 (诺言/兑现并行? :coverface1 不知道中文怎么表达了),良好的异常处理机制封装
上面这些话全是个人领悟了,具体的应该多写一些 c++ future 代码才可以理解异步,不然是不是看的不知所云呢? :speechless3
简单又傻瓜的例子
#include <future>
#include <iostream>

int main() {
std::future<void> autoLauncher = std::async(
std::launch::async, [] () {
std::cout << "Child Thread!\n";
for (int i=0; i<10; i++) {
std::cout << i << std::endl;
}
}
);

std::cout << "Main Thread\n";
}
编译: clang++ cxx-simple-async.cpp -stdlib=libc++ -std=c++1z -lthr -o prog1

例子 2:在 std::async 异步模式直接用原生的 std::condition_variable
#include <future>
#include <chrono>
#include <condition_variable>
#include <iostream>

int main() {
auto costlessSleep = [] () {
std::this_thread::sleep_for(std::chrono::nanoseconds(1));
};

std::mutex mutex;
bool ready = false;
std::condition_variable cv;

// 默 认 策 略 为 std::launch::async, 如 果 不 是 , 请 升 级 编 译 器
auto f = std::async([&cv, &mutex, &ready] () { // 引 用 捕 捉 cv, mutex, ready
std::unique_lock<std::mutex> lock(mutex);
for (int i=0; i<10; i++) {
std::cout << "Waiting ... (ready: "
<< std::boolalpha << ready << ")\n";
cv.wait(lock, [&ready] () {return ready==true;});
std::cout << "Notified. (ready: "
<< std::boolalpha << ready << ")\n";
ready = false;
std::cout << "ready=>false" << std::endl;
}
});

for (int i=0; i<12; i++) {
costlessSleep();
std::unique_lock<std::mutex> lock(mutex);
ready = true;
std::cout << "ready=>true" << std::endl;
lock.unlock();
cv.notify_one();
}
}
编译同上,运行结果如下:

代码: 全选

Waiting ... (ready: false)
ready=>true
Notified. (ready: true)
ready=>false
Waiting ... (ready: false)
ready=>true
Notified. (ready: true)
ready=>false
Waiting ... (ready: false)
ready=>true
Notified. (ready: true)
ready=>false
Waiting ... (ready: false)
ready=>true
Notified. (ready: true)
ready=>false
Waiting ... (ready: false)
ready=>true
Notified. (ready: true)
ready=>false
Waiting ... (ready: false)
ready=>true
Notified. (ready: true)
ready=>false
Waiting ... (ready: false)
ready=>true
Notified. (ready: true)
ready=>false
Waiting ... (ready: false)
ready=>true
Notified. (ready: true)
ready=>false
Waiting ... (ready: false)
ready=>true
Notified. (ready: true)
ready=>false
Waiting ... (ready: false)
ready=>true
Notified. (ready: true)
ready=>false
ready=>true
ready=>true
如果代码有编译问题或者运行后并行效果没有或者崩溃,那么你的编译器支持 c++14 (17) 力度不够。
FreeBSD 针对 LLVM 做了很多的移植和底层优化,因而编译 c++ 快速且代码稳定,clang 是支持 c++ 最好的编译器
回复

在线用户

正浏览此版面之用户: 没有注册用户 和 0 访客