> For the complete documentation index, see [llms.txt](https://wandersofb.gitbook.io/blog/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wandersofb.gitbook.io/blog/c++/duo-xian-cheng/condition_variable-and-semaphore.md).

# Condition\_variable & Semaphore

### condition\_variable

condition\_variable 能够阻塞一个线程，直至另一个线程修改共享变量并通知 condition\_variable。

```cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
 
std::mutex mutex;
std::condition_variable cv;
bool flag = true;

void f() {
    std::unique_lock<std::mutex> ul(mutex);
    while (flag) {
        std::cout << "I wait falg" << std::endl;
        // 线程休眠，释放锁。当它醒过来之后会获取锁。
        cv.wait(ul);
    }
    std::cout << "I wake up" << std::endl;
}

int main() {
    std::thread t(f);

    std::this_thread::sleep_for(std::chrono::milliseconds(30));

    int n = 10;
    while (n --) {
        std::cout << "---" << std::endl;
    }
    flag = false;
    // 唤醒随机一个沉睡线程
    cv.notify_one();
    t.join();
}
```

### semaphore


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wandersofb.gitbook.io/blog/c++/duo-xian-cheng/condition_variable-and-semaphore.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
