zoukankan      html  css  js  c++  java
  • C++多线程基础学习笔记(八)

    shared_futrue和futrue_status的用法

    shared_futrue是一个类模板,类似于futrue,不同的是它的成员函数get()可以使用多次,因为是复制数据,而futrue的get()则是转移数据,使用一次之后,就失效了。

    futrue_status是一个枚举类型,用来判断某个线程是否在规定时间执行完。

     1 #include <iostream>
     2 #include <future>
     3 #include <Windows.h>
     4 using namespace std;
     5 
     6 int mythread()
     7 {
     8     cout << "my thread:" << std::this_thread::get_id() << " start" << endl;
     9     cout << "waiting" << endl;
    10     Sleep(5000);
    11     cout << "my thread:" << std::this_thread::get_id() << " end" << endl;
    12     return 2;
    13 }
    14 int main()
    15 {
    16     // future_status的用法
    17     cout << "main thread:" << std::this_thread::get_id() << " start" << endl;
    18     std::future<int> result = std::async(std::launch::async, mythread);
    19     std::future_status status = result.wait_for(std::chrono::seconds(6));   //假设线程执行时间为6秒
    20     if (status == std::future_status::timeout)
    21         cout << "线程未执行完,超时了" << endl;
    22     else if (status == std::future_status::ready)
    23         cout << "线程成功执行" << endl;
    24     else
    25         cout << "线程被延迟执行" << endl;         //仅当async的第一个参数为std::launch::async才有可能出现
    26 
    27     // shared_future的用法,特点是它的成员函数get()是复制数据,所以get()可以使用多次
    28     std::packaged_task<int(void)> pt(mythread);
    29     thread t(std::ref(pt));
    30     t.join();
    31     std::shared_future<int> sf = pt.get_future();
    32     cout << sf.get() << endl;
    33     cout << sf.get() << endl;
    34 
    35     cout << "main thread:" << std::this_thread::get_id() << " end" << endl;
    36     system("pause");
    37     return 0;
    38 }

    顺便简单介绍std:;atomic的用法,它是一个类模板,使用它称为原子操作,和互斥量作用一样,同样是保护操作数据,不同的是原子操作是针对一个变量,互斥量是针对一段代码。

    使用方法:std::atomic<int> count = 0;   //声明一个int类型的变量,在多个线程操作该数据时,相当于每个线程操作数据的时候会给count加锁,保证了其他线程不会干扰它,保护了数据。

  • 相关阅读:
    整理:分页存储过程整理
    净利润-流通市值比率”与公司估值
    常见7种股票底部形态(图解)
    nginx
    移动成本分布1
    浅谈公开信息检索和判断能力
    股票技术分析 成交量与换手率专题
    成份股和成份股指数
    股票底部形态初探
    筹码拉抬派发法
  • 原文地址:https://www.cnblogs.com/main404/p/11273059.html
Copyright © 2011-2022 走看看