1

I have a thread that continuously read a global variable and there is another thread that occasionally update (write) global variable. What could be the best way to do that and what would be the cost? Is it possible if I do not put lock on read side and put a lock in writer side?

Thanks

user3260595
  • 53
  • 1
  • 8

2 Answers2

0

This scenario doesn't need any locks. You need locks when multiple threads modify state or when multiple threads read some state but you want to make sure that they read an up to date version or the same version.

Cristian Bidea
  • 648
  • 4
  • 12
  • This is wrong. You need locks (or some other synchronization mechanism) as soon as you have access from multple threads to a single resource, and one of the threads could modify this resource. And that is the case in the question. – viktorgt Mar 06 '14 at 08:58
  • read the original post again. He doesn't ask a theoretical question. He has one thread that writes a global variable and one thread that reads that. This doesn't need locking. Don't treat locking like a silver bullet! – Cristian Bidea Mar 06 '14 at 09:44
  • hello undefined behavior... http://stackoverflow.com/questions/7081176/one-reader-one-writer-some-general-questions-about-mutexes-and-atomic-builtins – viktorgt Mar 11 '14 at 08:20
  • Since this wasn't defined in the question, Cristian, you are wrong. Unless the read/write operations are *atomic*, even if you have one writer thread and one reader thread, you need sync mechanism. Consider a non atomic write operation, that changes the value in 2 steps. If the writer thread is preempted after the first step, allowing a reader thread CPU time, the state of the object is undefined. – Guy Oct 26 '14 at 10:42
  • Yes you're right. I was thinking int or pointer which is just a number the size of a register. While I was responding to you I wanted to make sure that writing an int is indeed atomic and surprise: "it may not be!" http://stackoverflow.com/questions/54188/are-c-reads-and-writes-of-an-int-atomic – Cristian Bidea Nov 20 '14 at 22:07
0

A lock protects the resource/variable and if the readers use it, the writer also should. If the global variable is a primitive type, I would suggest you make it an atomic using std::atomic<>. If it is a complex type, like a class, you should use a lock to ensure that your readers read a consistent state.

I have had much success with spinlocks in situations where you might expect low contention. But if your readers are reading at a high rate and you have many of them. A mutex or atomic should be used.

Arno Duvenhage
  • 1,820
  • 17
  • 34