Skip to content

Instantly share code, notes, and snippets.

@oconnor663
Created June 24, 2024 18:21
Show Gist options
  • Save oconnor663/c2074b06b469d4ddd9a556eb25663734 to your computer and use it in GitHub Desktop.
Save oconnor663/c2074b06b469d4ddd9a556eb25663734 to your computer and use it in GitHub Desktop.
folly::Synchronized race condition examples
#include <cstdint>
#include <cstdio>
#include <mutex>
#define GLOG_USE_GLOG_EXPORT
#include <folly/Synchronized.h>
class IntBumper {
public:
IntBumper(uint64_t &x) : m_ptr(&x) {}
void bump() { (*m_ptr)++; }
private:
uint64_t *m_ptr;
};
static folly::Synchronized<uint64_t, std::mutex> X;
void background_loop() {
for (int i = 0; i < 500'000; i++) {
IntBumper bumper = {*X.lock()};
bumper.bump();
}
}
int main() {
auto thread1 = std::thread(background_loop);
auto thread2 = std::thread(background_loop);
thread1.join();
thread2.join();
// BUG: This should print 1000000, but on my machine it prints something like 974918.
X.withLock([](auto &x) { printf("%ld\n", x); });
}
#include <cstdint>
#include <cstdio>
#include <mutex>
#define GLOG_USE_GLOG_EXPORT
#include <folly/Synchronized.h>
class IntBumper {
public:
IntBumper(uint64_t &x) : m_ptr(&x) {}
void bump() { (*m_ptr)++; }
private:
uint64_t *m_ptr;
};
static folly::Synchronized<uint64_t, std::mutex> X;
void background_loop() {
for (int i = 0; i < 500'000; i++) {
auto bumper = X.withLock([](auto &x) { return IntBumper{x}; });
bumper.bump();
}
}
int main() {
auto thread1 = std::thread(background_loop);
auto thread2 = std::thread(background_loop);
thread1.join();
thread2.join();
// BUG: This should print 1000000, but on my machine it prints something like 974918.
X.withLock([](auto &x) { printf("%ld\n", x); });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment