我是线程新手。我写了这个程序,我试图使用线程执行2个不同的函数。我试图通过一个接一个地更改target
和args
参数来使用相同的线程运行不同的函数:
import threading
import datetime
import Queue
a=Queue.Queue()
b=Queue.Queue()
q=Queue.Queue()
class MyThread(threading.Thread):
def __init__(self,q):
threading.Thread.__init__(self)
self.que=q
t1=threading.Thread(target=self.prints,args=(4,))
t2=threading.Thread(target=self.printy,args=(6,self.que,))
t1.start()
t2.start()
item=self.que.get()
print(item)
print "*"*30
it=item*2
print(it)
t1.join()
def main(self):
t3=threading.Thread(target=self.prints,args=(3,))
t4=threading.Thread(target=self.printy,args=(5,self.que,))
t3.start()
t4.start()
item=self.que.get()
print(item)
print "#"*30
it=item*2
print(it)
t2=threading.Thread(target=self.prints,args=(8,))
t4=threading.Thread(target=self.prints,args=(7,))
t2.start()
t4.start()
t2.join()
t3.join()
t4.join()
def prints(self,i):
while(i>0):
print "i="+str(i)+" "+str(datetime.datetime.now().time())+"\n"
i=i-1
def printy(self,i,b):
r=0
while(i<10):
print "i="+str(i)+" "+str(datetime.datetime.now().time())+"\n"
i=i+1
r=r+i
self.que.put(r)
if __name__=='__main__':
MyThread(a).main()
它执行时没有抛出任何错误,也给了我想要的输出,但我想知道是否:
答案 0 :(得分:1)
from multiprocessing import Pool
def f(x):
return x*x*x
def b(x):
return x*x
if __name__ == '__main__':
p = Pool(5)
print(p.map(f, [1, 2, 3]))
print(p.map(b, [1, 2, 3]))
>> [1, 8, 27]
>> [1, 4, 9]
请注意,无法在ipython会话中运行此示例!
使用线程编辑:
import threading
import queue
q = queue.deque()
def niceFunc1(data):
return reversed(data)
def niceFunc2(data):
return "Hey there :%s" % data
q.append( (niceFunc1,"gude") )
q.append( (niceFunc1,"test") )
q.append( (niceFunc2,"test") )
q.append( (niceFunc2,"123") )
def worker():
for each in q:
print(each[0](each[1]))
t=threading.Thread(target=worker)
t.start()
t2=threading.Thread(target=worker)
t2.start()