线程--promise furture 同步

http://www.cnblogs.com/haippy/p/3279565.html

std::promise 类介绍

promise 对象可以保存某一类型 T 的值,该值可被 future 对象读取(可能在另外一个线程中),因此 promise 也提供了一种线程同步的手段。在 promise 对象构造时可以和一个共享状态(通常是std::future)相关联,并可以在相关联的共享状态(std::future)上保存一个类型为 T 的值。

可以通过 get_future 来获取与该 promise 对象相关联的 future 对象,调用该函数之后,两个对象共享相同的共享状态(shared state)

  • promise 对象是异步 Provider,它可以在某一时刻设置共享状态的值。
  • future 对象可以异步返回共享状态的值,或者在必要的情况下阻塞调用者并等待共享状态标志变为 ready,然后才能获取共享状态的值。
#include <iostream>       // std::cout
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future

void print_int(std::future<int>& fut) {
    int x = fut.get(); // 获取共享状态的值.
    std::cout << "value: " << x << ‘\n‘; // 打印 value: 10.
}

int main ()
{
    std::promise<int> prom; // 生成一个 std::promise<int> 对象.
    std::future<int> fut = prom.get_future(); // 和 future 关联.
    std::thread t(print_int, std::ref(fut)); // 将 future 交给另外一个线程t.
    prom.set_value(10); // 设置共享状态的值, 此处和线程t保持同步.
    t.join();
    return 0;
}
#include <iostream>       // std::cin, std::cout, std::ios
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <exception>      // std::exception, std::current_exception

void get_int(std::promise<int>& prom) {
    int x;
    std::cout << "Please, enter an integer value: ";
    std::cin.exceptions(std::ios::failbit);   // throw on failbit
    try {
        std::cin >> x;                         // sets failbit if input is not int
        prom.set_value(x);
    }
    catch (std::exception&) {
        prom.set_exception(std::current_exception());
    }
}

void print_int(std::future<int>& fut) {
    try {
        int x = fut.get();
        std::cout << "value: " << x << ‘\n‘;
    }
    catch (std::exception& e) {
        std::cout << "[exception caught: " << e.what() << "]\n";
    }
}

int main()
{
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();

    std::thread th1(get_int, std::ref(prom));
    std::thread th2(print_int, std::ref(fut));

    th1.join();
    th2.join();
    return 0;
}
时间: 2024-08-12 08:02:37

线程--promise furture 同步的相关文章

线程:Exchanger同步工具

可以在对中对元素进行配对和交换的线程的同步点,类似于交易,A拿着钱到达指定地点,B拿着物品到达指定地点,相互交换,然后各自忙各自的事去了. 1 package ch03; 2 3 import java.util.concurrent.Exchanger; 4 5 public class ExchangerTest { 6 7 public static void main(String[] args) { 8 final Exchanger<String> changer = new Ex

线程:CountDownLatch同步工具

一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待. 类似计数器,当计数器的值为0时,继续往下执行. 1 package ch03; 2 3 import java.util.Random; 4 import java.util.concurrent.CountDownLatch; 5 import java.util.concurrent.ExecutorService; 6 import java.util.concurrent.Executors; 7 8

线程互斥与同步

能解决下面的问题,基本上就能理解线程互斥与同步了. 子线程循环10次,主线程循环100次,接着子线程循环10,主线程循环100次.如此往复循环50次. 1 package cn.lah.thread; 2 3 public class TraditionalThreadCommunication { 4 5 public static void main(String[] args) { 6 7 final Business business = new Business(); 8 new Th

C# 线程之间的同步

1.通过Join方法,暂停当前线程 Thread secondThread = new Thread(new ThreadStart(ThreadMethod)); secondThread.Start(); ... secondThread.Join(); 2.通过启动APM异步操作的方法,得到一个IAsyncResult对象,通过它有三种方法使得两个线程同步. public interface IAsynResult { object AsyncState{get; } WaitHandle

线程:CyclicBarrier同步工具类

一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点.比如公司组织活动出去玩,需要在公司门口一起搭车去.每个人从家里出发去公司门口,到达的时间肯定先后不一样,所以公司的车要一直等待,等所有人到齐后,才开车出发.CyclicBarrier就类似这样的功能,当所有线程到达"屏蔽点"的时候,才往下走. 具体等待多少根线程到达,可以在构造方法里指定CyclicBarrier(int parties). 当你的parties设为3的时候,假设只有2根线程到达此处,那程序会一直在此等待.

vc++高级班之多线程篇[7]---线程间的同步机制②

//示例代码: CStringArray g_ArrString; UINT __cdecl ThreadProc(LPVOID lpParameter) { int startIdx = (int)lpParameter; for (int idx = startIdx; idx < startIdx+100; ++idx) { CString str; str.Format(_T("%d"), idx); g_ArrString.Add(str); } return 0; }

线程的资源同步问题

卖出的票为负数的情况: class MyThread22 implements Runnable {     private int ticket = 10;     public void run() {         for (int i = 0; i < 100; i++) {             if (ticket > 0) {                 try {                    Thread.sleep(1000);               

vc++高级班之多线程篇[6]---线程间的同步机制①

①.线程同步的必要性: int g_Num = 0; UINT __cdecl ThreadProc(LPVOID lpParameter) { for (int idx = 0; idx < 100; ++idx) { g_Num = g_Num+1; CString strNum; strNum.Format(_T("%d"), g_Num); g_Num = g_Num-1; } return 0; } void CThreadTestDlg::OnBnClickedBtn

进程 线程 多线程 并发 同步异步

进程 线程 多线程 并发 同步异步 很多人对进程,线程,多线程,并发,同步,异步等概念感到困惑,这都是大学没好好听课的缘故啊.咱在这里帮感到概念给感到困惑的同学复习下. 程序 程序用来描述计算机所完成的独立功能,并在时间上严格地按前后次序相继地进行计算机操作序列集合,是一个静态概念. 进程 并发执行的程序在执行过程中分配和管理资源的基本单位.是一个动态的执行过程. 进程的静态描述 进程控制块PCB 有关程序段 该程序员对齐进行操作的数据结构集 进程控制块PCB 进程控制块PCB是系统管制进程存在