C++中線程同步有幾種方式,剝離開系統(tǒng)層面,只談語言的話耘沼。常用的是mutex
加鎖同步和future
捕捉同步功戚。
本文簡單談一下自己對future
的用法理解。
首先需要知道future
是什么。future
是C++中對于線程處理的庫,可以進行線程異步處理和同步線程。
- 線程異步處理可以參照例子:
#include <iostream> // std::cout
#include <future> // std::async, std::future
#include <chrono> // std::chrono::milliseconds
using namespace std;
// a non-optimized way of checking for prime numbers:
bool is_prime (int x) {
for (int i=2; i<x; ++i) if (x%i==0) return false;
return true;
}
int main ()
{
// call function asynchronously:
future<bool> fut = async (is_prime,444444443);
// do something while waiting for function to set future:
cout << "checking, please wait";
chrono::milliseconds span (100);
while (fut.wait_for(span)==future_status::timeout)
cout << '.' << flush;
bool x = fut.get(); // retrieve return value
cout << "\n444444443 " << (x?"is":"is not") << " prime.\n";
return 0;
}
- 線程同步可以參照例子:
#include <iostream>
#include <string> // string
#include <thread> // thread
#include <future> // promise, future
#include <chrono> // seconds
using namespace std;
void recv(future<int> *future){
try {
cout << future->get() << endl;
} catch (future_error &e){
cerr << "err : " << e.code() << endl << e.what() << endl;
}
}
void send(promise<int> *promise){
int i = 0;
while (i < 5){
cout << "send while" << endl;
++i;
this_thread::sleep_for(chrono::seconds(1));
}
promise->set_value("hello another thread");
}
int main(int argc, char **argv) {
promise<string> promise;
future<string> future = promise.get_future();
thread thread_send(send, &promise);
thread thread_recv(recv, &future);
thread_send.join();
thread_recv.join();
return 0;
}