Skip to content

Instantly share code, notes, and snippets.

@LusainKim
Created January 5, 2016 22:26
Show Gist options
  • Save LusainKim/7e476cd9e5d20939c1d7 to your computer and use it in GitHub Desktop.
Save LusainKim/7e476cd9e5d20939c1d7 to your computer and use it in GitHub Desktop.
atomic test
#include <windows.h>
#include <iostream>
#include <thread>
#include <memory>
#include <map>
#include <atomic>
using namespace std;
atomic_bool g_booleanVariable = false;
unsigned int cnts = 0;
CRITICAL_SECTION cs;
map<int, pair<int, bool>> m;
void __stdcall threadmain(int threadID)
{
Sleep(1);
bool arrboolVariable[5] = { false };
int arrTime[5] = { 0 };
for (int i = 0; i < 5; ++i)
{
Sleep(1);
atomic_store(&g_booleanVariable, !g_booleanVariable);
// g_booleanVariable = !g_booleanVariable;
arrboolVariable[i] = g_booleanVariable.load();
InterlockedExchangeAdd(&cnts, 1);
arrTime[i] = cnts;
// cout << g_booleanVariable << endl;
}
EnterCriticalSection(&cs);
for (int i = 0; i < 5; ++i)
m[arrTime[i]] = make_pair(threadID, arrboolVariable[i]);
LeaveCriticalSection(&cs);
}
#define TASTCASE 25
int main()
{
InitializeCriticalSection(&cs);
bool TestFlag = false;
cout << "testcase is " << TASTCASE << "." << endl;
for (int testcase = 0; testcase < TASTCASE; ++testcase)
{
// if (TestFlag) break;
g_booleanVariable = false;
cnts = 0;
m.clear();
thread *trd[8];
int start_t = GetTickCount();
for (int i = 0; i < 8; ++i)
trd[i] = new thread{ threadmain, i };
for (int i = 0; i < 8; ++i)
trd[i]->join();
int end_t = GetTickCount();
// cout << "[Time] : " << end_t - start_t << " s" << endl;
// cout << endl;
bool chkTest = m.begin()->second.second;
for (auto p : m)
{
if (chkTest != p.second.second) { TestFlag = true; cout << "[testcase "<< testcase + 1 << ", " << p.first << " times] atomic fail! " << boolalpha << p.second.second << endl; break; }
chkTest = !chkTest;
// cout << "[thread ID " << p.second.first << "] : " << boolalpha << p.second.second << endl;
}
// cout << boolalpha << p.second << endl;
}
DeleteCriticalSection(&cs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment