C++11实现线程同步

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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 引用自多线程编程指南应用程序里面多个线程的存在引发了多个执行线程安全访问资源的潜在问题。两个线程同时修改同一资源有...
    Mitchell阅读 2,022评论 1 7
  • 多线程三个特征:原子性、可见性以及有序性. 同步锁 /并发锁/ 读写锁,显示锁, ReentrantLock与Co...
    架构师springboot阅读 1,968评论 0 5
  • 对于从多个执行线程安全访问资源,应用程序中多个线程的存在会导致潜在的问题。修改相同资源的两个线程可能会以出乎意料的...
    渐z阅读 399评论 0 0
  • 多线程 多线程技术大家都很了解,而且在项目中也比较常用。比如开启一个子线程来处理一些耗时的计算,然后返回主线程刷新...
    Sunxb阅读 1,116评论 0 1
  • 多个线程同时使用共享对象,这种情形被称为竞争条件(Race Condition),竞争条件是多线程环境中非常常见的...
    LH_晴阅读 3,483评论 0 2