Skip to content

Instantly share code, notes, and snippets.

@fovtran
Created August 13, 2021 19:01
Show Gist options
  • Save fovtran/ca8e816eddaff52e25bf7a69e5c6d0d7 to your computer and use it in GitHub Desktop.
Save fovtran/ca8e816eddaff52e25bf7a69e5c6d0d7 to your computer and use it in GitHub Desktop.
comparing mfence and mutes
// g++ -O3 -lpthread -march=athlon64-sse3 -std=c++17 barier_and_mutexes.cpp -o barrier_and_mutexes
#include <stdio.h>
#include <cstdint>
#include <cstdlib>
#include <atomic>
#include <vector>
#include <thread>
#include <mutex>
#include <cassert>
int const nMaxThreads = std::thread::hardware_concurrency();
std::vector<std::thread> threads;
std::atomic<void*> head;
std::atomic<void*> data;
std::atomic<int*> p=nullptr;
typedef struct {int v,c; }myData;
// myData data2;
void modifyData(std::atomic<void*> d){}
void _proceedTest(std::atomic<void*> data2){
static std::mutex mtx;
std::unique_lock<std::mutex> lk(mtx);
modifyData(&data2);
lk.unlock();
}
int main(){
int* regularVar1=0;
regularVar1++;
//head.store(0, std::memory_order_relaxed);
head.store(regularVar1,std::memory_order_seq_cst);
//std::atomic_thread_fence(std::memory_order_seq_cst);
data = head.load(std::memory_order_relaxed);
//std::atomic_thread_fence(std::memory_order_seq_cst);
p = regularVar1;
//first thread
{
int* nonatomic_p=(int*) malloc(16*1024*sizeof(int));
for(int i=0;i<16*1024;++i)
nonatomic_p[i]=42;
p=nonatomic_p;
}
//second thread reads
{
while (p==nullptr)
{}
assert(p[1234]==42);//1234-random idx in array
}
for (int iThread = 0; iThread < nMaxThreads; ++iThread)
{
threads.push_back(std::thread(_proceedTest, &head));
}
for (auto& th : threads) th.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment