V
V
Vladimir Grabko2016-05-16 19:35:40
go
Vladimir Grabko, 2016-05-16 19:35:40

Thread safety. Is it possible to make the lock object global?

Let's say I create a global variable
var maxDataLock sync.Mutex
now I can use it

maxDataLock.Lock()
Event[name](ps)
maxDataLock.Unlock()

So is it right to make locks or for each function it is necessary to make its own variable?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
#
#algooptimize #bottize, 2016-05-16
@lucifer-m

Locks must compete where there is a race to access the same data. It is not necessary to use the same lock for independent operations, this can lead to performance degradation. There are other nuances, but this is the main thing. Don't forget to read about deadlock and atomic operations, there's also freelock. I hope I understood the question correctly. :-)

G
Gizmothron, 2016-05-31
@Gizmothron

If these are different mutexes, then they give different locks.
Or reduce everything to a call to one common function (inside which the blocking occurs).
Or, if the code that handles locked objects is complex, use channels.
Or, use lock-free algorithms with package atomic. You can read about it in a series of articles https://habrahabr.ru/post/196834

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question