c++多线程--进阶

c++多线程–进阶

std::async和std::futurre

  1. 含义:异步执行

  2. 参数: 参 数 = { s t d : : l a u n c h : : a s y n c 将在一个新线程中运行 s t d : : l a u n c h : : d e f e r r e d 随着future调用get()后才在同一线程开始执行 参数= \begin{cases} std::launch::async& \text{将在一个新线程中运行}\\ std::launch::deferred& \text{随着future调用get()后才在同一线程开始执行} \end{cases} ={std::launch::asyncstd::launch::deferred将在一个新线程中运行随着future调用get()后才在同一线程开始执行

  3. 用法:配合std::future

  4. 例子

#include <chrono>
#include <future>
#include <iostream>

int main() {

    auto begin = std::chrono::system_clock::now();
    auto asyncLazy = std::async(std::launch::deferred, [] { return  std::chrono::system_clock::now(); });
    auto asyncEager = std::async(std::launch::async, [] { return  std::chrono::system_clock::now(); });
    std::this_thread::sleep_for(std::chrono::seconds(1));
    auto lazyStart = asyncLazy.get() - begin;
    auto eagerStart = asyncEager.get() - begin;
    auto lazyDuration = std::chrono::duration<double>(lazyStart).count();
    auto eagerDuration = std::chrono::duration<double>(eagerStart).count();

    std::cout << "asyncLazy evaluated after : " << lazyDuration << " seconds." << std::endl;
    std::cout << "asyncEager evaluated after: " << eagerDuration << " seconds." << std::endl;
}

std::shared_mutex(C++17)

  1. 含义:共享锁

  2. 用法:允许多个线程以共享方式持有读锁,只允许一个线程持有写锁

  3. 如果不使用C++17可以使用boost

  4. 例子

#include <iostream>
#include <mutex>  // For std::unique_lock
#include <shared_mutex>
#include <thread>

std::shared_mutex g_mutex;

int count = 0;

void readLoop()
{
    while (true) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        g_mutex.lock_shared();
        std::cout << count << std::endl;
        g_mutex.unlock_shared();
    }
}

void writeLoop()
{
    while (true) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        g_mutex.lock();
        count++;
        std::cout << count << std::endl;
        g_mutex.unlock();
    }
}

int main()
{
    std::thread(writeLoop).detach();
    std::thread(readLoop).detach();
    std::thread(readLoop).detach();

    std::this_thread::sleep_for(std::chrono::seconds(10));
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值