CPPPROGLIB Telegram 6138
🍬 Потоки могут общаться через condition_variable

Чтобы один поток ожидал другого можно воспользоваться condition_variable.


🍴 Пошаговое решение:

1️⃣ Создайте condition_variable и mutex
2️⃣ Поток ждёт через wait()
3️⃣ Другой поток сигналит через notify_one/notify_all

#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>

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

void worker() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return ready; }); // Ждём сигнала

std::cout << "Worker started!\n";
}

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

std::this_thread::sleep_for(std::chrono::seconds(1));

{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one(); // Будим поток

t.join();
return 0;
}


❗️ Частая ошибка: Забыть проверять условие в wait()

💡 Совет: Всегда передавайте предикат в wait()


Библиотека C/C++ разработчика

#буст
Please open Telegram to view this post
VIEW IN TELEGRAM
3👍2🙏1



tgoop.com/cppproglib/6138
Create:
Last Update:

🍬 Потоки могут общаться через condition_variable

Чтобы один поток ожидал другого можно воспользоваться condition_variable.


🍴 Пошаговое решение:

1️⃣ Создайте condition_variable и mutex
2️⃣ Поток ждёт через wait()
3️⃣ Другой поток сигналит через notify_one/notify_all

#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>

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

void worker() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return ready; }); // Ждём сигнала

std::cout << "Worker started!\n";
}

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

std::this_thread::sleep_for(std::chrono::seconds(1));

{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one(); // Будим поток

t.join();
return 0;
}


❗️ Частая ошибка: Забыть проверять условие в wait()

💡 Совет: Всегда передавайте предикат в wait()


Библиотека C/C++ разработчика

#буст

BY Библиотека C/C++ разработчика | cpp, boost, qt


Share with your friend now:
tgoop.com/cppproglib/6138

View MORE
Open in Telegram


Telegram News

Date: |

To edit your name or bio, click the Menu icon and select “Manage Channel.” To view your bio, click the Menu icon and select “View channel info.” Matt Hussey, editorial director of NEAR Protocol (and former editor-in-chief of Decrypt) responded to the news of the Telegram group with “#meIRL.” As five out of seven counts were serious, Hui sentenced Ng to six years and six months in jail. When choosing the right name for your Telegram channel, use the language of your target audience. The name must sum up the essence of your channel in 1-3 words. If you’re planning to expand your Telegram audience, it makes sense to incorporate keywords into your name.
from us


Telegram Библиотека C/C++ разработчика | cpp, boost, qt
FROM American