Python多线程多进程的例子

看了些python的书,但是一直没弄明白多线程,多进程在实际中是怎么用的,不知各位有没有具体代码或者文档给推荐下。

比如现在有一个文件,文件里每行是一个URL,现在要实现用张程池,开启20个线程,要求每执行完一条,就从文件里再读一条加到任务队列(不能一次性把文件都读到内存,要一次读一行),一直保持20个线程去执行。这样的话具体的代码该怎么写?或者是多线程操作rabbitmq或者redis的类似代码,求解。

阅读 5.4k
2 个回答
def func(line):
    pass

p = multiprocessing.Pool(20)
p.map(func,file('yourfile'))

我的demo仅做参考,并不限于此方法:

# coding=utf8
import threading
import time
import random
class Test(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        global threadlist
        time.sleep(random.randint(1,5))
        threadlist.remove(self)#线程运行结束,则在threadlist中remove掉

threadlist = []  # 创建一个列表来保存多线程
for i in range(20):
    threadlist.append(Test())
for each in threadlist:
    each.start()
while True:
    time.sleep(0.2)
    length=len(threadlist)
    num=20-len(threadlist)
    print '当前线程数%d'%length
    if length == 20:
        print 'pass'
    else:
        for i in range(20-length):
            threadlist.append(Test())
        for each in threadlist[-num:]:
            each.start()
        print 'appended'
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题