请教一个Python 多线程程序流程的问题
本人接触Python不久,最近开发中需要处理一种状况由一个循环线程全程对一个变量CP 进行价值,周期为一秒一次
然后又有N个线程分别以不同的周期对这个CP 进行不同的减值,
我研究了半天,貌似用GIL 的话要过多的等待分支线程回来,可能会造成不同步的错误结果
特来求教,请高手指点一下,我现在完全没思路啊。。。。谢谢了 ~~~
#!/usr/bin/env python import Queue import threading import time import random q=Queue.Queue(0) NUM_WORKERS = 3 class MyThread(threading.Thread): """A worker thread.""" def __init__(self, input, worktype): self._jobq = input self._work_type = worktype threading.Thread.__init__(self) def run(self): """ Get a job and process it. Stop when there's no more jobs """ while True: if self._jobq.qsize()>0: job = self._jobq.get() worktype=self._work_type self._process_job(job,worktype) else: break def _process_job(self, job,worktype): """ Do useful work here. worktype: let this thread do different work 1,do list 2,do item 3,,, """ doJob(job) def doJob(job): """ do work function 1 """ time.sleep(random.random()*3) print "doing ",job if __name__=='__main__': print "begin..." #put some work to q for i in range(NUM_WORKERS*2): q.put(i) #print total job q's size print "job q'size",q.qsize() #start threads to work for x in range(NUM_WORKERS): MyThread(q,x).start() #if q is not empty, wait #while q.qsize()>0: # time.sleep(0.1)
import threading from time import sleep,ctime def Capacity(MaxCapacity,Recharge_time):#增加CP 的方法 global cp while 1: print 'cp:',cp cp = cp+MaxCapacity/Recharge_time print 'now cp:',cp sleep(1) def Pao(cpxh,atime):#减少CP 的方法 while 1: global cp print 'pao:',cp cp = cp -cpxh print 'pao now cp',cp sleep(atime) def main(): print '\nGO' threads=[] threads2=[] t=threading.Thread(target=Capacity,args=(100,100)) threads.append(t) #print threads threads[0].setDaemon(True)#守护线程 threads[0].start()#启动累加线程 print 'cp thread over!',cp for i in range(5): p=threading.Thread(target=Pao,args=(2,3)) threads2.append(p) print 'pao%s ----------go!'%(threads2[i]),cp threads2[i].start() print 'pao%s ----------end'%(threads2[i]),cp cp=100 if __name__=='__main__': main()