1

I have following code

int i; //gobal var

Thread1:
{
...
  i=some value;
}

Thread2:
{
  if (i==2) dosomething();
  else dosomethingelse();
  i = 4;
}

I want to write it to be thread safe without using synchronization objects and in C++ standard way.

my questions is how to have a variable to read/write access by different threads with out using synchronization? my requirement is have a bool variable which can have true or false.

Is volatile variable is atomic.

Please note that i am not supposed to use any libraires like TBB which has atomic variable.

Reason for asking this question we don't want to take and release semphore every time we access the variable in thread, as this variable changed not very often.

iammilind
  • 68,093
  • 33
  • 169
  • 336
venkysmarty
  • 11,099
  • 25
  • 101
  • 184
  • 3
    Read up on Boost Atomics and c++0x thread specs. `I want to write it to be thread safe without using synchronization objects` sic, anything else you _want_ :) - you can, for varying definitions of safe. If fuzzy is good enough and your code can handle occasionally reading 'phantom' values, you don't need locking as long as there is a single writer. (This might be useful for realtime monitoring mechanisms). Also if a variable doesn't change often, it seems like a good candidate for a condition variable. – sehe Sep 15 '11 at 09:11
  • can u pls show with simple example how to use condition variable in above scenario. my understanding is that condition variable blocks instead of moving forward, but i want to loop – venkysmarty Sep 15 '11 at 09:17
  • 1
    How many threads are reading the variable and how many threads are potentially changing it? – NPE Sep 15 '11 at 09:34
  • only two threads, one is reading and other is writing – venkysmarty Sep 15 '11 at 10:21

1 Answers1

0

Well your code does not have any meaning right now. Becaues you are basically saying`

Thread2:
{
  if (i==2) dosomething();
  //let's do something if i is 2 at the moment I am reading it.
  else dosomethingelse();
  i = 4;
}`

It is ok. But if you are doing something with i then you are in trouble. If not, and if you are asking whether accessing i is atomic or not, it depends on cpu architecture. For example for x86 and x64 it is atomic. Read this.

Community
  • 1
  • 1
ali_bahoo
  • 4,732
  • 6
  • 41
  • 63
  • actually i gave just simple code made from my project, basically i have two threads one is reading and other is writing – venkysmarty Sep 15 '11 at 10:22
  • @venkysmarty: How about `dosomething()` and `dosomethingelse`? Are they using the global var `i`? `dosomething() {std::cout << i << "\n";}` ? – ali_bahoo Sep 15 '11 at 10:27