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

前端 未结 18 1911
孤独总比滥情好
孤独总比滥情好 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:03

    Yes and no.

    Thread safety is a little bit more than just making sure your shared data is accessed by only one thread at a time. You have to ensure sequential access to shared data, while at the same time avoiding race conditions, deadlocks, livelocks, and resource starvation.

    Unpredictable results when multiple threads are running is not a required condition of thread-safe code, but it is often a by-product. For example, you could have a producer-consumer scheme set up with a shared queue, one producer thread, and few consumer threads, and the data flow might be perfectly predictable. If you start to introduce more consumers you'll see more random looking results.

提交回复
热议问题