问题
I have seen the terms contention
and race
are used interchangeably when it comes to thread's state(at critical section). Are they same?
回答1:
"Contention" usually refers to the situation where two or more threads need to lock the same lock. We say that the lock is "contested" or maybe, "heavily contested," if there is a significant probability of any thread being forced to wait when it tries to acquire the lock.
"Race," "Race condition," and "Data race" are phrases whose meanings have changed over time, and which may have different meaning to people working in different programming languages. Any time somebody uses one of those words/phrases, be sure you understand how they are using it.
"Race," in the most general way, describes the situation where the outcome of some operation depends on how threads are scheduled. A race could be benign if every possible outcome is an acceptable outcome. For example, if two or more threads race to acquire a lock, and the order in which some things get written to a file depend on which thread gets there first, but nobody cares about the order...
*BUT*
..."Race condition" and "Data race" now are used by some programmers to describe any of the multitude of subtle problems that can occur when multi-threaded code that is compiled by modern, optimizing compilers, and run on modern multi-processor hardware accesses shared variables without some kind of protection.*
Even if it's not obvious that the threads are "racing" to access some unprotected, shared variable, it still can be bad, and bad in ways that didn't exist ten or more years ago.** I can't name them all.
If you're writing C++ programs, the C++ language standard deals with it by simply saying that any access to a shared variable without protection is a "data race," and any data race is "undefined behavior," and if your program invokes undefined behavior, then it is WRONG! Doesn't matter if it happens to work for you, It's wrong, and it's your fault that it's wrong, and if you ship it to a customer and six months later the customer sues you because they upgraded their OS and their whole e-commerce system went to ****, then that's all your fault because... "data race."
* I'm talking about mutex locks, and/or Atomic<foobar>
data types.
** Beware advice and examples from old text books.
来源:https://stackoverflow.com/questions/61919294/thread-contention-vs-race