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));
}