Skip to content

Instantly share code, notes, and snippets.

@Joshhua5 Joshhua5/Work.h Secret
Last active Nov 15, 2016

Embed
What would you like to do?
Work False Sharing
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
//
// Protheus
//
// Created by Joshua Waring on 4/06/2015.
//
#include <iostream>
#include <thread>
//#define FALSE_SHARING
#ifdef FALSE_SHARING
void worker(volatile unsigned long long* work_done, int thread_id, volatile bool* working, volatile bool* start) {
while (!start);
while (working)
work_done[thread_id]++;
}
const int THREAD_COUNT = 4;
int main() {
volatile bool working = true;
volatile bool start = false;
volatile unsigned long long work_done[THREAD_COUNT];
memset((void*)work_done, 0, sizeof(unsigned long long) * THREAD_COUNT);
for (int x = 0; x < THREAD_COUNT; x++)
std::thread(&worker, work_done, x, &working, &start).detach();
start = true;
std::this_thread::sleep_for(std::chrono::seconds(5));
// We check while the threads working, to fit in with
// the use case
for (int x = 0; x < THREAD_COUNT; x++)
std::cout << work_done[x] << std::endl;
working = false;
return 0;
}
#else
int worker(volatile unsigned long long** work_done, volatile bool* working, volatile bool* start) {
volatile unsigned long long value = 0;
*work_done = &value;
while (!start);
while (working)
value++;
return value;
}
const int THREAD_COUNT = 4;
int main() {
volatile bool working = true;
volatile bool start = false;
volatile unsigned long long* work_done[THREAD_COUNT];
memset(work_done, 0, sizeof(unsigned long long) * THREAD_COUNT);
for (int x = 0; x < THREAD_COUNT; x++)
std::thread(&worker, &work_done[x], &working, &start).detach();
start = true;
std::this_thread::sleep_for(std::chrono::seconds(5));
// We check while the threads working, to fit in with
// the use case
for (int x = 0; x < THREAD_COUNT; x++)
std::cout << *work_done[x] << std::endl;
working = false;
return 0;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.