multithreading - Making a Queue for a function so it only runs once at a time in python -


i have multithreaded function, write same log file. how can make function (maybe function decorator) add execution of writing log file queue. small example:

#!/usr/bin/python  import thread import time  # define function thread def print_time( threadname, delay):    count = 0    while count < 5:       time.sleep(delay)       count += 1       writetolog(threadname, time.ctime(time.time()))       print "%s: %s" % ( threadname, time.ctime(time.time()) )  # create 2 threads follows try:    thread.start_new_thread( print_time, ("thread-1", 2, ) )    thread.start_new_thread( print_time, ("thread-2", 4, ) ) except:    print "error: unable start thread"  def writetolog(threadname, time):    self.filewriter = open("log.txt", "w")    self.filewriter.write("threadname: " + threadname + "\n")    self.filewriter.write("time: " + time + "\n")    self.filewriter.close() 

how can make function writetolog add queue when executed? every time both threads call writetolog function error because other writetolog function (from other thread) closed file. when having global variable writer, closed in end, output this:

threadname: thread1 threadname: thread2 time: 9:50am time: 9:50am 

and output want has this:

threadname: thread-1 time: 9:50am threadname: thread-2 time: 9:50am 

concurrency access shared resource known problem. python thread provide mechanism avoid issues. use python locks : http://docs.python.org/2/library/threading.html#lock-objects lock used synchronize access shared resource :

lock = lock()  lock.acquire() # block if lock held ... access shared resource lock.release() 

more information : http://effbot.org/zone/thread-synchronization.htm

search "python synchronization"


Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -