1

I believe it is thread-safe to replace one-shot threading.Event variables with Boolean variables even if the GIL were to be removed. I would like confirmation.

For example, to replace the former with the latter:

class Test(threading.Thread):
  def __init__(self):
    self.stop_var = threading.Event()

  def run(self):
    while not self.stop_var.is_set():
      do_work()

  def stop(self):
    self.stop_var.set()
class Test(threading.Thread):
  def __init__(self):
    self.stop_var = False

  def run(self):
    while not self.stop_var:
      do_work()

  def stop(self):
    self.stop_var = True

As stop_var is set only once (across both threads) there is no data race and it forevermore will remain True. There is technically a race condition between setting and testing stop_var but the outcome - stopping the thread - is invariant across both outcomes. So either the loop runs an extra time or not, but the program is guaranteed to stop. I should also point out the Locks used by Event suffer the same race condition, as locks cannot guarantee an ordering.

Now it would be problematic to repeatedly toggle the Boolean. Then you should use locks prevent data races and possibly notify/wait to prevent race conditions... in other words, use Events.

This question is often asked but not yet addressed. For example this gets sidetracked by the GIL, failing to answer the question. Whereas this answer is just plain wrong, right? Per the comment, "Is it time to revisit this answer?", I believe, Yes.

[1] Are "data races" and "race condition" actually the same thing in context of concurrent programming

[2] Race Condition vs. Data Race

user19087
  • 1,899
  • 1
  • 16
  • 21

0 Answers0