c++多線程–進階
std::async和std::futurre
-
含義:異步執行
-
參數:
-
用法:配合std::future
-
例子
#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)
-
含義:共享鎖
-
用法:允許多個線程以共享方式持有讀鎖,只允許一個線程持有寫鎖
-
如果不使用C++17可以使用boost
-
例子
#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));
}