1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | promise<string> val; static void threadPromiseFuture(){ thread ta([](){ future<string> fu = val.get_future(); cout << "waiting promise->future" << endl; cout << fu.get() << endl; }); thread tb([](){ this_thread::sleep_for( chrono::milliseconds(100) ); val.set_value("promise is set"); }); ta.join(); tb.join(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | static mutex g_mutex; static void threadPackagedTask(){ auto run = [=](int index){ { lock_guard<mutex> _(g_mutex); cout << "tasklet " << index << endl; } this_thread::sleep_for( chrono::seconds(10) ); return index * 1000; }; packaged_task<int(int)> pt1(run); packaged_task<int(int)> pt2(run); thread t1([&](){pt1(2);} ); thread t2([&](){pt2(3);} ); int f1 = pt1.get_future().get(); int f2 = pt2.get_future().get(); cout << "task result=" << f1 << endl; cout << "task result=" << f2 << endl; t1.join(); t2.join(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | static long do_sum(vector<long> *arr, size_t start, size_t count){ static mutex _m; long sum = 0; for(size_t i = 0; i < count; i++){ sum += (*arr)[start + i]; } { lock_guard<mutex> _(_m); cout << "thread " << this_thread::get_id() << ", count=" << count << ", sum=" << sum << endl; } return sum; } static void threadAsync(){ # define COUNT 1000000 vector<long> data(COUNT); for(size_t i = 0; i < COUNT; i++){ data = random() & 0xff; } // vector< future<long> > result; size_t ptc = thread::hardware_concurrency() * 2; for(size_t batch = 0; batch < ptc; batch++){ size_t batch_each = COUNT / ptc; if (batch == ptc - 1){ batch_each = COUNT - (COUNT / ptc * batch); } result.push_back(async(do_sum, &data, batch * batch_each, batch_each)); } long total = 0; for(size_t batch = 0; batch < ptc; batch++){ total += result[batch].get(); } cout << "total=" << total << endl; } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |