Skip to content

Instantly share code, notes, and snippets.

@termoshtt
Created May 18, 2014 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save termoshtt/96eaddc21775c0722c4a to your computer and use it in GitHub Desktop.
Save termoshtt/96eaddc21775c0722c4a to your computer and use it in GitHub Desktop.
C++で簡単非同期処理(std::thread,std::async) ref: http://qiita.com/termoshtt/items/d3cb7fe226cdd498d2ef
auto th1 = std::thread([]{ do_long_work(); });
do_another_things();
th1.join();
double a;
auto th1 = std::thread([&a]{ a = long_calc(); });
do_another_things();
th1.join();
std::cout << a << std::endl; // 1.0
#include <vector>
#include <future>
#include <iostream>
int main(int argc, char const *argv[]) {
std::vector<int> v(10);
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i) {
threads.push_back(std::thread([i, &v] { v[i] = i * i; }));
}
for (std::thread &th : threads) {
th.join();
}
for (int i : v) {
std::cout << i << std::endl;
}
return 0;
}
$ g++ -std=c++11 source.cpp -pthread
$ clang++ -std=c++11 source.cpp -pthread
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
auto result = std::async(std::launch::async, [] { return long_calc(); });
do_another_things();
std::cout << result.get() << std::endl;
#include <future>
#include <iostream>
#include <vector>
int main(int argc, char const *argv[]) {
std::vector<std::future<int> > v;
for (int i = 0; i < 10; ++i) {
v.push_back(std::async([i] { return i * i; }));
}
for (auto &val : v) {
std::cout << val.get() << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment