Sobes.tech
Junior — Middle

Kuidas saab vältida vastastikuseid lukustusi mitme niidiga keskkonnas?

sobes.tech AI

Vastus AI-lt

To prevent mutual blocking (deadlocks) in a multithreaded environment, several approaches can be used:

  • Avoid nested locks: try not to acquire multiple mutexes at the same time.
  • Define an order for resource acquisition: always lock mutexes in the same order in all threads.
  • Use timeouts when acquiring locks: if the lock is not obtained within a certain time, release already acquired resources and try again.
  • Apply higher-level synchronization constructs: for example, channels in Go, which allow avoiding explicit locks.

Example of ordered mutex acquisition in Go:

var mu1, mu2 sync.Mutex

func safeFunc() {
    mu1.Lock()
    defer mu1.Unlock()

    mu2.Lock()
    defer mu2.Unlock()

    // work with resources
}

It is important that all functions acquiring these mutexes do so in the same order.