如何将单线程代码转换为多线程代码



我有一个问题,我将currentPlace字符串声明为全局字符串,但我认为如果我在转换为str后是正确的,它会覆盖全局设置,对吗?我对此一直不知所措。任何帮助都将不胜感激,谢谢。

代码:

from proxy_checker import ProxyChecker
import json
import threading




# define an empty list
places = []
threads = []

def check():
global check
# open file and read the content in a list
with open('prox_list.txt', 'r') as filehandle:
for line in filehandle:
# remove linebreak which is the last character of the string
global currentPlace
currentPlace = line[:-1]
# add item to the list
places.append(currentPlace)
checker = ProxyChecker()
output = checker.check_proxy(str(currentPlace))
print(str(currentPlace) + " " + str(output))


with open('output_prox.txt', 'w') as filehandle:
json.dump(currentPlace, filehandle)



for i,link in enumerate(str(currentPlace)):
t = threading.Thread(target=check, args=(i, link))
t.start()
threads.append(t)

for thread in threads:
thread.join()

您可以使用multiprocessing.dummy.Pool类作为多线程的简单接口。(它被称为"伪",因为它不是真正的多处理,它只是生活在同一个模块中。(

编写辅助函数,使其接受参数并返回值(就像编写任何其他函数一样(,并完全避免全局变量。使用Pool#map方法将辅助函数映射到输入值列表上:

from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
from proxy_checker import ProxyChecker
def check(place):
checker = ProxyChecker()
output = checker.check_proxy(place)
return place, output
places = []
with open('prox_list.txt', encoding='utf8') as filehandle:
for line in filehandle:
places.append(line[:-1])
pool = ThreadPool(cpu_count())
results = pool.map(check, places)
print(results)

最新更新