Skip to content

Instantly share code, notes, and snippets.

@juehan
Created August 18, 2012 12:08
Show Gist options
  • Select an option

  • Save juehan/3386422 to your computer and use it in GitHub Desktop.

Select an option

Save juehan/3386422 to your computer and use it in GitHub Desktop.
Use of C++11 atomic to handle shared resource under multi threaded environment.
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <atomic>
using namespace std;
void bar(int id, int& value)
{
value++;
cout<<"id ["<<id<<"] : "<<value<<endl;
}
void atomic_bar(int id, atomic<int>& atomicValue)
{
atomicValue++;
cout<<"atomic id ["<<id<<"] : "<<atomicValue<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout.sync_with_stdio(true); //is this really works under VS2012?
int count = 0;
thread t1(bar, 1, count);
thread t2(bar, 2, count);
thread t3(bar, 3, count);
t1.join();
t2.join();
t3.join();
cout<<"<== atomic test ==>"<<endl;
atomic<int> atomic_count(0);
thread s1(atomic_bar, 1, std::ref(atomic_count));
thread s2(atomic_bar, 2, std::ref(atomic_count));
thread s3(atomic_bar, 3, std::ref(atomic_count));
s1.join();
s2.join();
s3.join();
return 0;
}
//program output goes...
//id [1] : 1
//id [2] : 1
//id [3] : 1
//<== atomic test ==>
//atomic id [1] : 1
//atomic id [2] : 2
//atomic id [3] : 3
//계속하려면 아무 키나 누르십시오 . . .
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment