C++中线程同步有几种方式,剥离开系统层面,只谈语言的话。常用的是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;
}