【python】多线程
https://docs.python.org/2/library/multiprocessing.html
https://docs.python.org/2/library/threading.html
http://www.coder4.com/archives/3352
import multiprocessing import time from time import sleep import random def func(msg): for i in xrange(3): print msg time.sleep(1) class A: def __init__(self,i): sleep(int(random.random()*10)) print i class B: def __init__(self): pass def b(self): print __name__ if __name__ == "__main__": pool = multiprocessing.Pool(processes=4) for i in xrange(10): msg = i pool.apply_async(A, (msg, )) pool.close() pool.join() print "Sub-process(es) done." cb = B() cb.b()
注意:if __name__ == "__main__": 必不可少
2.7版本对类方法的多线程支持不好,变通实现方案
import multiprocessing import time from time import sleep import random def func(msg): for i in xrange(3): print msg time.sleep(1) class A(): def __init__(self): print 'A' def a(self,i): sleep(int(random.random()*10)) print i return 10+i class C: def __init__(self,i): sleep(int(random.random()*10)) print i def multi(i): k=A() return k.a(i) class B: def __init__(self): pass def b(self): print __name__ #k = A() if __name__ == "__main__": pool = multiprocessing.Pool(processes=4) #k = C for i in xrange(10): z = pool.apply_async(multi,(i,)) print z.get() pool.close() pool.join() print "Sub-process(es) done." cb = B() cb.b()
http://pymotw.com/2/multiprocessing/