Skip to content

Instantly share code, notes, and snippets.

@ayushgun
Last active September 26, 2023 03:01
Show Gist options
  • Save ayushgun/4a0104d287ad737ae7236affcaed0153 to your computer and use it in GitHub Desktop.
Save ayushgun/4a0104d287ad737ae7236affcaed0153 to your computer and use it in GitHub Desktop.
Example of the usage of std::mutex in writing thread-safe code. The mutex locks prior to modifying the vector member of the log class. This makes any other threads also modifying the vector via the addCode method wait until the mutex unlocks. Thus, only one thread can call addCode at a time. Would be better to use a std::lock_guard.
#include <functional>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
// Thread-safe implementation of a log
class Log {
private:
std::vector<int> codeLog;
std::mutex mtx;
public:
void addCode(int code) {
// Uses a mutex to lock write access to the vector in the method, ensuring
// thread-safety
mtx.lock();
codeLog.push_back(code);
mtx.unlock();
}
std::vector<int> getCodeLog() const { return codeLog; }
};
// Adds codes from [1, 50] to a log object
void task(Log& log) {
constexpr int max_code = 50;
for (int i = 1; i <= max_code; ++i) {
log.addCode(i);
}
}
int main() {
Log log;
std::thread t1(task, std::ref(log));
std::thread t2(task, std::ref(log));
t1.join();
t2.join();
for (int code : log.getCodeLog()) {
std::cout << code << '\n';
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment