multithreading - how to share global variables across threads in python? -


i want end loop running in separate thread using global variable. code not seem stop thread in loop. expect program not print more '.' after 2 seconds, still runs indefinitely.

am doing fundamentally wrong here?

import time import threading run = true  def foo():     while run:         print '.',  t1 = threading.thread(target=foo) t1.run() time.sleep(2) run = false print 'run=false' while true:     pass 

  1. you executing foo() on main thread calling t1.run(). should call t1.start() instead.

  2. you have 2 definitions of foo() - doesn't matter, shouldn't there.

  3. you don't put sleep() inside thread loop (in foo()). bad, since hogs processor. should @ least put time.sleep(0) (release time slice other threads) if not sleep little longer.

here's working example:

import time import threading run = true  def foo():     while run:         print '.',         time.sleep(0)  t1 = threading.thread(target=foo) t1.start() time.sleep(2) run = false print 'run=false' while true:     pass 

Comments