C ++ and promise of the future

Role and future promise is to pass data between different threads. It can also be done using the pointer to transfer data, but the pointers are very dangerous because the mutex can not block access to the pointer; pointer and data transfer method is fixed, if you change the data type, you also need to change about the interface, more trouble ; promise support for generics operations more convenient programming process.

Suppose a thread for a thread 2 data, then use the following combination:

Thread 1 initializes a future target object and a promise, promise to transfer the thread 2, a commitment corresponding to thread 1, thread 2; corresponding to a future accepts a promise for the future value of the thread 2 acquires the transmitting
thread 2 acquires promise , you need to transfer data related to this promise, then thread the future 1 can get the data.
If you want to get data thread 1, thread 2 and data not shown, the thread 1 block until the data reaches the thread 2

 

/** @file  20190815future.cpp
*  @note  
*  @brief
*  @author 
*  @date   2019-8-15
*  @note   
*  @history
*  @warning
*/
#include <iostream>
#include <functional>
#include <future>
#include <thread>
#include <chrono>
#include <cstdlib>

void thread_set_promise(std::promise<int>& promiseObj) {
    std::cout << "In a thread, making data...\n";
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    promiseObj.set_value(35);
    std::cout << "Finished\n";
}

int main() {
    std::promise<int> promiseObj;
    std::future<int> futureObj = promiseObj.get_future();
    std::thread t(&thread_set_promise, std::ref(promiseObj));
    std::cout << futureObj.get() << std::endl;
    t.join();

    system("pause");
    return 0;
}

 

the async (future advanced packaging and thread)

/** @file  futureIsPrime.cpp
*  @note   
*  @brief
*  @author 
*  @date   2019-8-15
*  @note   
*  @history
*  @warning
*/
// future example
#include <iostream>       // std::cout
#include <future>         // std::async, std::future
#include <chrono>         // std::chrono::milliseconds

// 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:
  std::future<bool> fut = std::async (is_prime,444444443);

  // do something while waiting for function to set future:
  std::cout << "checking, please wait";
  std::chrono::milliseconds span (100);
  while (fut.wait_for(span)==std::future_status::timeout)
    std::cout << '.' << std::flush;

  bool x = fut.get();     // retrieve return value

  std::cout << "\n444444443 " << (x?"is":"is not") << " prime.\n";

  return 0;
}

 

Guess you like

Origin www.cnblogs.com/guxuanqing/p/11360572.html