how can i update a shared variable between different threading.Thread in python?
lets say that i have 5 threads working down a Queue.Queue(). after the queue is done i want to do an other operation but i want it to happen only once.
is it possible to share and update a variable betweeen the threads. so when Queue.empty() is True this event gets fired but if one of the threads is doing it i dont want the others to do do that too because i would get wrong results.
EDIT
i have a queue which reflects files on the filesystem.
the files are uploaded to a site by the threads and while each thread is uploading the file it updates a set() of keywords i got from the files.
when the queue is empty i need to contact the site and tell it to update the keyword counts. right now each thread does this and i get an update for each thread which is bad.
i also tried to empty the set but it doesnt work.
keywordset = set()
hkeywordset = set()
def worker():
while queue:
if queue.empty():
if len(keywordset) or len(hkeywordset):
# as soon as the queue is empty we send the keywords and hkeywords to the
# imageapp so it can start updating
apiurl = update_cols_url
if apiurl[-1] != '/':
apiurl = apiurl+'/'
try:
keywords = []
data = dict(keywords=list(keywordset), hkeywords=list(hkeywordset))
post = dict(data=simplejson.dumps(data))
post = urllib.urlencode(post)
urllib2.urlopen(apiurl, post)
hkeywordset.clear()
keywordset.clear()
print 'sent keywords and hkeywords to imageapp...'
except Exception, e: print e
# we get the task form the Queue and process the file based on the action
task = queue.get()
print str(task)
try:
reindex = task['reindex']
except:
reindex = False
data = updater.process_file(task['filename'], task['action'], task['fnamechange'], reindex)
# we parse the images keywords and hkeywords and add them to the sets above for later
# processing
try:
for keyword in data['keywords']:
keywordset.add(keyword)
except: pass
try:
for hkw in data['hkeywords']:
hkeywordset.add(hkw)
except:pass
queue.task_done()
for i in range(num_worker_threads):
t = threading.Thread(target=worker)
t.daemon = True
t.start()
while 1:
line = raw_input('type \'q\' to stop filewatcher... or \'qq\' to force quit...\n').strip()
this is what i was trying basically. but of course the part of queue.empty() gets exectued as many times as threads i have.