日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

python多线程资源共享_Python:关于多处理/多线程和共享资源的问题

發布時間:2024/9/30 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python多线程资源共享_Python:关于多处理/多线程和共享资源的问题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

以下是我目前發現的最簡單的多線程示例:import multiprocessing

import subprocess

def calculate(value):

return value * 10

if __name__ == '__main__':

pool = multiprocessing.Pool(None)

tasks = range(10000)

results = []

r = pool.map_async(calculate, tasks, callback=results.append)

r.wait() # Wait on the results

print results

我有兩個列表和一個索引來訪問每個列表中的元素。第一個列表中的第i個位置與第二個列表中的第i個位置相關。我沒有使用口述,因為名單是有序的。在

我所做的是:

^{pr2}$

所以,用這個例子,我想可以把一個函數變成這樣:#global variables first_list, second_list, i

first_list, second_list, i = None, None, 0

#initialize the lists

...

#have a function to do what the loop did and inside it increment i

def function:

#do stuff

i += 1

但是,這使得i成為共享資源,我不確定這是否安全。在我看來,我的設計并沒有很好地支持這種多線程方法,但我不確定如何修復它。在

下面是一個我想要的工作示例(編輯您想要使用的圖像):import multiprocessing

import subprocess, shlex

links = ['http://www.example.com/image.jpg']*10 # don't use this URL

names = [str(i) + '.jpg' for i in range(10)]

def download(i):

command = 'wget -O ' + names[i] + ' ' + links[i]

print command

args = shlex.split(command)

return subprocess.call(args, shell=False)

if __name__ == '__main__':

pool = multiprocessing.Pool(None)

tasks = range(10)

r = pool.map_async(download, tasks)

r.wait() # Wait on the results

總結

以上是生活随笔為你收集整理的python多线程资源共享_Python:关于多处理/多线程和共享资源的问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。