python - Different way to implement this threading? -


i'm trying out threads in python. want spinning cursor display while method runs (for 5-10 mins). i've done out code wondering how it? don't use globals, assume there better way?

c = true   def b():     j in itertools.cycle('/-\|'):         if (c == true):             sys.stdout.write(j)             sys.stdout.flush()             time.sleep(0.1)             sys.stdout.write('\b')         else:             return  def a():     global c     #code stuff here 5-10 minutes     #simulate sleep     time.sleep(2)     c = false  thread(target = a).start() thread(target = b).start() 

edit:

another issue when processing ends last element of spinning cursor still on screen. \ printed.

you use events: http://docs.python.org/2/library/threading.html

i tested , works. keeps in sync. should avoid changing/reading same variables in different threads without synchronizing them.

#!/usr/bin/python  threading import thread threading import event import time import itertools import sys  def b(event):     j in itertools.cycle('/-\|'):         if not event.is_set():             sys.stdout.write(j)             sys.stdout.flush()             time.sleep(0.1)             sys.stdout.write('\b')         else:             return  def a(event):     #code stuff here 5-10 minutes     #simulate sleep     time.sleep(2)     event.set()  def main():     c = event()     thread(target = a, kwargs = {'event': c}).start()     thread(target = b, kwargs = {'event': c}).start()  if __name__ == "__main__":     main() 

related 'kwargs', python docs (url in beginning of post):

class threading.thread(group=none, target=none, name=none, args=(), kwargs={}) ...     kwargs dictionary of keyword arguments target invocation. defaults {}. 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -