具有共享变量(值)的Python多处理Pool.apply_async

具有共享变量(值)的Python多处理Pool.apply_async,第1张

具有共享变量(值)的Python多处理Pool.apply_async

如错误消息所述,您无法

multiprocessing.Value
通过泡菜。但是,您可以使用
multiprocessing.Manager().Value

import multiprocessingimport urllib2import randomimport myurllist    #list of all destination urls for all 10 serversimport timeimport socbindtry   #script that binds various virtual/aliased client ips to the scriptdef send_request3(response_time, error_count):    #function to send requests from alias client ip 1    opener=urllib2.build_opener(socbindtry.BindableHTTPHandler3)    #bind to alias client ip1    try:        tstart=time.time()        for i in range(myurllist.url): x=random.choice(myurllist.url[i]) opener.open(x).read() print "file downloaded:",x response_time.append(time.time()-tstart)    except urllib2.URLError, e:        with error_count.get_lock(): error_count.value += 1def send_request4(response_time, error_count):    #function to send requests from alias client ip 2    opener=urllib2.build_opener(socbindtry.BindableHTTPHandler4)    #bind to alias client ip2    try:        tstart=time.time()        for i in range(myurllist.url): x=random.choice(myurllist.url[i]) opener.open(x).read() print "file downloaded:",x response_time.append(time.time()-tstart)    except urllib2.URLError, e:        with error_count.get_lock(): error_count.value += 1#50 such functions are defined here for 50 clientsdef func(response_time, error_count):    pool=multiprocessing.Pool(processes=2*multiprocessing.cpu_count())    args = (response_time, error_count)    for i in range(5):        pool.apply_async(send_request3, args=args)        pool.apply_async(send_request4, args=args)#append 50 functions here    pool.close()    pool.join()    print"All work Done..!!"    returnif __name__ == "__main__":    m=multiprocessing.Manager()    response_time=m.list()    #some shared variables    error_count=m.Value('i',0)    start=float(time.time())    func(response_time, error_count)    end=float(time.time())-start    print end

其他一些注意事项:

  1. 使用
    Pool
    750个流程不是一个好主意。除非您使用具有数百个CPU内核的服务器,否则这将使您的计算机不堪重负。这样可以更快,更省力地使用更少的进程。更像
    2 * multiprocessing.cpu_count()
  2. 最佳做法是,应将需要使用的所有共享参数明确传递给子进程,而不要使用全局变量。这增加了在Windows上运行代码的机会。
  3. 看起来您的所有
    send_request*
    函数几乎都做同样的事情。为什么不仅仅执行一个函数并使用一个变量来决定
    socbindtry.BindableHTTPHandler
    使用哪个呢?这样可以避免 大量代码重复。
  4. 您递增的
    error_count
    方式不是进程/线程安全的,并且容易受到竞争条件的影响。您需要使用锁来保护增量(就像我在上面的示例代码中所做的那样)。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5649047.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存