0

Hi while i'm programming i had to do a choice :

while not cont_flag :
    pass

and using a Event object :

if not const_flag.is_set() :
    const_flag.wait()

i want to know if there is a difference in performance between the two methode

KarimS
  • 3,812
  • 9
  • 41
  • 64
  • Blocking IO won't turn your CPU into a toaster. Instead the user process will simply wait for the system to say "hey, you have data, do something" (in which case the IO call "unblocks"). – user2864740 Feb 13 '14 at 17:32
  • @user2864740 Please avoid answering questions in comments. You could post that as an answer instead. – John Kugelman Feb 13 '14 at 17:33

3 Answers3

3

There is. The first method is called busy waiting and is very different from blocking. In busy waiting, the CPU is being used constantly as the while loop is executed. In blocking, the thread is actually suspended until a wake-up condition is met.

See also this discussion: What is the difference between busy-wait and polling?

Community
  • 1
  • 1
TypeIA
  • 16,916
  • 1
  • 38
  • 52
2

The first one is referred to as busy waiting, it will eat up 100% of the CPU time while waiting. It's a way better practice to have some signalling mechanism to communicate events (e.g. something's done).

Pavel
  • 7,436
  • 2
  • 29
  • 42
1

Python only allows a single thread to execute at a time, regardless of how many cpus your system may have. If multiple threads are ready to run, python will switch among them periodically. If you "busy wait" as in your first example, that while loop will eat up much of the time that your other threads could use for their work. While the second solution is far superior, if you end up using the first one, add a modest sleep to it.

while not cont_flag:
    time.sleep(.1)
tdelaney
  • 73,364
  • 6
  • 83
  • 116