C++20新特性的小細節,你掌握了嗎?
本文轉載自微信公眾號「程序喵大人」,作者程序喵大人。轉載本文請聯系程序喵大人公眾號。
之前我整理過一篇C++20新特性的文章全網首發!!C++20新特性全在這一張圖里了,里面提到過latch、barrier和semaphore,但是沒有詳細介紹過三者的作用和區別,這里詳細介紹下。
latch
這個可能大多數人都有所了解,這就是我們經常會用到的CountDownLatch。用于使一個線程先阻塞,等待其他線程完成各自的工作后再繼續執行。
CountDownLatch是通過計數器實現,計數器的初始值為線程的數量。每當一個線程完成了自己的任務后,計數器的值就會減1。當計數器值到達0時,它表示所有的線程已經完成了任務,然后等待的線程就可以打斷阻塞去繼續執行任務。
自己之前實現過一個CountDownLatch,源碼大概這樣:
- CountDownLatch::CountDownLatch(int32_t count) : count_(count) {}
- void CountDownLatch::CountDown() {
- std::unique_lock<std::mutex> lock(mutex_);
- --count_;
- if (count_ == 0) {
- cv_.notify_all();
- }
- }
- void CountDownLatch::Await(int32_t time_ms) {
- std::unique_lock<std::mutex> lock(mutex_);
- while (count_ > 0) {
- if (time_ms > 0) {
- cv_.wait_for(lock, std::chrono::milliseconds(time_ms));
- } else {
- cv_.wait(lock);
- }
- }
- }
- int32_t CountDownLatch::GetCount() const {
- std::unique_lock<std::mutex> lock(mutex_);
- return count_;
- }
barrier
許多線程在阻塞點阻塞,當到達阻塞點的線程達到一定數量時,會執行完成的回調,然后解除所有相關線程的阻塞,然后重置線程計數器,繼續開始下一階段的阻塞。
假設有很多線程并發執行,并在一個循環中執行一些計算。進一步假設一旦這些計算完成,需要在線程開始其循環的新迭代之前對結果進行一些處理。
看以下示例代碼(摘自cppreference):
- #include <barrier>
- #include <iostream>
- #include <string>
- #include <thread>
- #include <vector>
- int main() {
- const auto workers = { "anil", "busara", "carl" };
- auto on_completion = []() noexcept {
- // locking not needed here
- static auto phase = "... done\n" "Cleaning up...\n";
- std::cout << phase;
- phase = "... done\n";
- };
- std::barrier sync_point(std::ssize(workers), on_completion);
- auto work = [&](std::string name) {
- std::string product = " " + name + " worked\n";
- std::cout << product; // ok, op<< call is atomic
- sync_point.arrive_and_wait();
- product = " " + name + " cleaned\n";
- std::cout << product;
- sync_point.arrive_and_wait();
- };
- std::cout << "Starting...\n";
- std::vector<std::thread> threads;
- for (auto const& worker : workers) {
- threads.emplace_back(work, worker);
- }
- for (auto& thread : threads) {
- thread.join();
- }
- }
可能的輸出如下:
- Starting...
- anil worked
- carl worked
- busara worked
- ... done
- Cleaning up...
- busara cleaned
- carl cleaned
- anil cleaned
- ... done
semaphore
信號量,這個估計大家都很熟悉,本質也是個計數器,主要有兩個方法:
acquire():遞減計數器,當計數器為零時阻塞,直到計數器再次遞增。
release():遞增計數器(可傳遞具體數字),并解除在acquire調用中的線程的阻塞。
示例代碼如下:
- #include <iostream>
- #include <thread>
- #include <chrono>
- #include <semaphore>
- std::binary_semaphore
- smphSignalMainToThread(0),
- smphSignalThreadToMain(0);
- void ThreadProc() {
- smphSignalMainToThread.acquire();
- std::cout << "[thread] Got the signal\n"; // response message
- using namespace std::literals;
- std::this_thread::sleep_for(3s);
- std::cout << "[thread] Send the signal\n"; // message
- smphSignalThreadToMain.release();
- }
- int main() {
- std::thread thrWorker(ThreadProc);
- std::cout << "[main] Send the signal\n"; // message
- smphSignalMainToThread.release();
- smphSignalThreadToMain.acquire();
- std::cout << "[main] Got the signal\n"; // response message
- thrWorker.join();
- }
- 輸出如下:
- [main] Send the signal
- [thread] Got the signal
- [thread] Send the signal
- [main] Got the signal
信號量也可以當作條件變量使用,這個我估計大家應該知道怎么做。
打完收工。