c++多線程--進階

c++多線程–進階

std::async和std::futurre

  1. 含義:異步執行

  2. 參數:={std::launch::async將在一個新線程中運行std::launch::deferred隨着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));
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章