What is the meaning of the term “thread-safe”?

前端 未结 18 2004
孤独总比滥情好
孤独总比滥情好 2020-11-22 13:51

Does it mean that two threads can\'t change the underlying data simultaneously? Or does it mean that the given code segment will run with predictable results when multiple t

18条回答
  •  甜味超标
    2020-11-22 14:24

    An easier way to understand it, is what make code not thread-safe. There's two main issue that will make a threaded application to have unwanted behavior.

    • Accessing shared variable without locking
      This variable could be modified by another thread while executing the function. You want to prevent it with a locking mechanism to be sure of the behavior of your function. General rule of thumb is to keep the lock for the shortest time possible.

    • Deadlock caused by mutual dependency on shared variable
      If you have two shared variable A and B. In one function, you lock A first then later you lock B. In another function, you start locking B and after a while, you lock A. This is a potential deadlock where first function will wait for B to be unlocked when second function will wait for A to be unlocked. This issue will probably not occur in your development environment and only from time to time. To avoid it, all locks must always be in the same order.

提交回复
热议问题