Frage

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

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top