溫馨提示×

c++ wait_for有哪些功能

c++
小樊
121
2024-11-24 12:03:53
欄目: 編程語言

wait_for 是 C++ 標準庫 <chrono> 中的一個函數,它用于等待給定的時間間隔。這個函數的主要功能是阻塞當前線程直到指定的時間到達或者發生某個特定事件。wait_for 的常見用途包括:

  1. 延遲執行:通過傳遞一個時間間隔(如 std::chrono::secondsstd::chrono::milliseconds),你可以讓當前線程暫停一段時間。這對于實現定時任務或延時操作非常有用。
#include <iostream>
#include <chrono>
#include <thread>

int main() {
    std::cout << "Waiting for 5 seconds...\n";
    std::this_thread::sleep_for(std::chrono::seconds(5));
    std::cout << "5 seconds have passed.\n";
    return 0;
}
  1. 輪詢檢查wait_for 也可以與條件變量結合使用,以實現輪詢檢查某個條件是否滿足。當條件不滿足時,線程會等待一段時間,然后再次檢查。這比忙等待(busy-waiting)更節省資源。
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id(int id) {
    std::unique_lock<std::mutex> lck(mtx);
    while (!ready) {  // 如果 ready 為 false, 則等待
        cv.wait(lck);  // 當前線程被阻塞, 當全局變量 ready 變為 true 之后,
    }
    // ...
}

int main() {
    std::thread threads[10];
    // spawn 10 threads:
    for (int i = 0; i < 10; ++i)
        threads[i] = std::thread(print_id, i);

    std::cout << "10 threads ready to race...\n";
    {
        std::lock_guard<std::mutex> lck(mtx);
        ready = true;  // set the flag to true
    }
    cv.notify_all();  // wake up all threads

    for (auto &th : threads) th.join();

    return 0;
}

在這個例子中,print_id 函數會等待直到全局變量 ready 被設置為 true。主線程在設置 readytrue 之后,通過 cv.notify_all() 喚醒所有等待的線程。

需要注意的是,wait_for 函數會阻塞當前線程,直到指定的時間間隔到達或者發生某個特定事件。如果在這段時間內沒有其他線程調用 cv.notify_one() 來喚醒等待的線程,那么等待的線程將會一直阻塞下去。因此,在使用 wait_for 時,通常需要配合條件變量來實現更復雜的同步邏輯。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女