Skip to content

Instantly share code, notes, and snippets.

@byBretema
Last active November 2, 2019 10:38
Show Gist options
  • Save byBretema/8236e687f347ed49428a8923464b164a to your computer and use it in GitHub Desktop.
Save byBretema/8236e687f347ed49428a8923464b164a to your computer and use it in GitHub Desktop.
Snippet for C++ multi-thread stuff
#pragma once
#include <functional>
#include <mutex>
class safe_mt {
private:
std::mutex m_mutex;
std::condition_variable m_condvar;
public:
safe_mt() {}
void wait(const std::function<bool(void)> &fn) {
std::unique_lock lock(m_mutex);
m_condvar.wait(lock, fn);
}
void run(const std::function<void(void)> &fn, bool all = true) {
std::lock_guard lock(m_mutex);
fn();
all ? m_condvar.notify_all() : m_condvar.notify_one();
}
};
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include "safe_mt.hpp"
auto test_fn = []() {
int v = 0;
safe_mt safemt;
std::vector<std::thread> tpool;
tpool.emplace_back(std::thread{[&]() {
safemt.wait([&]() { return v > 0; });
std::cout << "1" << std::endl;
}});
tpool.emplace_back(std::thread{[&]() {
safemt.wait([&]() { return v > 1; });
std::cout << "2" << std::endl;
}});
auto fn = [&]() { safemt.run([&]() { v++; }, true); };
tpool.emplace_back(std::thread{fn});
tpool.emplace_back(std::thread{fn});
for (auto &th : tpool)
if (th.joinable())
th.join();
return 1;
};
int main() {
std::ios_base::sync_with_stdio(false);
safe_mt safemt;
auto a = 0;
std::thread t1{[&]() { safemt.run([&]() { a = test_fn(); }); }};
std::thread t2{[&]() {
safemt.wait([&]() { return a > 0; });
std::cout << "-\n3" << std::endl;
}};
t2.join();
t1.join();
}
// OUTPUT
// ---------
// 1 2
// 2 OR 1
// - -
// 3 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment