Skip to content

Instantly share code, notes, and snippets.

@mboedigh
Created November 27, 2023 17:04
Show Gist options
  • Save mboedigh/cf530dbffc70e01e741936fbecfa51dd to your computer and use it in GitHub Desktop.
Save mboedigh/cf530dbffc70e01e741936fbecfa51dd to your computer and use it in GitHub Desktop.
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
std::mutex mutex;
std::condition_variable cv;
bool workerThreadsFinished = false;
void workerThread() {
// Perform the worker thread's task
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lock(mutex);
workerThreadsFinished = true;
cv.notify_one();
}
}
int main() {
std::vector<std::thread> threads;
// Create and start worker threads
for (int i = 0; i < 4; ++i) {
threads.emplace_back(workerThread);
}
while (true) {
{
std::unique_lock<std::mutex> lock(mutex);
while (!workerThreadsFinished) {
cv.wait(lock);
}
workerThreadsFinished = false;
}
// Perform the main loop's work
std::cout << "Main loop iteration" << std::endl;
}
for (std::thread& thread : threads) {
thread.join();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment