我怎样才能更新不同线程之间的共享变量?python中的线程?python线程和共享变量
可以说我有5个线程工作在一个Queue.Queue()。队列完成后,我想做其他操作,但我希望它只发生一次。
是否有可能共享和更新线程之间的变量。所以当Queue.empty()为True时,这个事件被触发,但如果其中一个线程正在做它,我不希望其他人也这样做,因为我会得到错误的结果。
编辑
我有一个反映文件系统上的文件的队列。 文件上传到网站的线程和每个线程正在上传文件时,它更新了我从文件中获得的关键字集()。
当队列为空时,我需要联系站点并告诉它更新关键字计数。现在每个线程都这样做,我得到每个线程的更新是坏的。 我也尝试清空设置,但它不起作用。
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()
这就是我基本上想要的。但是当然queue.empty()的部分获得的执行次数与我拥有的线程一样多。
抱歉,但我真的不明白你的意思。 – aschmid00 2010-11-06 21:56:05
@ aschmid00:__sorry,但我真的不明白你的意思,这对我来说也是一样的?我的意思是帮助,但我认为,而我只是让你更困惑,我想我会删除这个答案,除非你给我们更多的细节,你想做什么,也许一些代码来了解更多的问题,希望你找到你的答案:) – mouad 2010-11-06 22:01:52
谢谢!我会尽快尝试并让你知道。 – aschmid00 2010-11-07 14:20:04