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}

  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));
}
发布了80 篇原创文章 · 获赞 68 · 访问量 7539

猜你喜欢

转载自blog.csdn.net/weixin_44048823/article/details/104071779