0

In any multithreaded application, that has one writer thread and one reader thread, Do we need to use lockers ? For example:

public void example::increase() {
   counter++;
}

public int example::getValue() {
   return counter;
}
  1. In this example, Do we need lockers ?
  2. The app can crash if we will not use lockers ?

Thanks

Azil
  • 457
  • 2
  • 5
  • 10
  • You need either locks or atomic operations, and each has a very specific use case that cannot reliably be "the answer" to this due to the vagueness of your question. We don't even know what `counter` is. – WhozCraig Mar 18 '15 at 18:53
  • Assuming counter is an integer: If you want to have a synchronized value (in time) you need atomic access (std::atomic), but no lock of a mutex, If not (the reader thread does not care), you do not need atomic access. –  Mar 18 '15 at 19:04
  • Assuming a fundamental type for counter, the app won't crash, but the veracity of getValue() will be dubious at best. – tipaye Mar 18 '15 at 19:23

1 Answers1

0

Well it works and not depending on your purpose. If you don't really care whether the reader will read the old, unincremented value or the new, incremented value, then it wouldn't be much of a problem. While if you do then you need to place locks and maybe enforce order.

For example, you cannot expect that such a code:

counter= 0
CreateThread(Writer)
CreateThread(Writer)
CreateThread(Reader)

You cannot expect in this case that the reader will read 2, it might read 0, 1 or 2.

AbdulRahman AlHamali
  • 1,851
  • 1
  • 14
  • 18