-
-
Save Joshhua5/5b6e9e50b3318244656b to your computer and use it in GitHub Desktop.
Work False Sharing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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