美文网首页
C++11实现线程同步

C++11实现线程同步

作者: Virtualer | 来源:发表于2019-08-29 16:49 被阅读0次

    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;
    }
    

    相关文章

      网友评论

          本文标题:C++11实现线程同步

          本文链接:https://www.haomeiwen.com/subject/jehpectx.html