如何在Python中将“ for”更改为多线程池

时间:2019-02-27 18:54:21

标签: python multithreading

所以我制作了一个我想一直循环直到关闭的程序。所以现在我使用这段代码;

while True:
  a = start();
  for aaa in a:
    check(a[aaa], 0)

但这太慢了。我怎样才能使用它对此进行多线程处理(这是我的尝试,这当然是不正确的);

pool = ThreadPool(threads)
results = pool.map(check, a, 0)

我用threads = 1尝试了该代码。它什么也没给。有人可以帮我吗?

====编辑====

启动功能;

def start():
    global a
    url = "URL_WAS_HERE" // receives a json like {"a":56564356, "b":654653453} etc. etc.
    r = requests.get(url)
    a = json.loads(r.text)
    return a

检查功能;

def check(idd, tries):
  global checked
  global snipe
  global notworking
  if tries < 1:
    checked = checked+1
    url = "URL_WAS_HERE"+str(idd) // Receives json with extra information about the id
    r = requests.get(url)
    try:
        b = json.loads(r.text)
        if b['rap'] > b['best_price']:
            difference = b['rap']-b['best_price'];
            print(str(idd)+" has a "+str(difference)+ "R$ difference. Price: "+str(b['best_price'])+" //\\ Rap: "+str(b['rap']))
            snipe = snipe+1

    except:
        time.sleep(1)
        tries = tries+1
        notworking = notworking+1
        check(idd, tries)
  settitle("Snipes; "+str(snipe)+" //\\ Checked; "+str(checked)+" //\\ Errors; "+str(notworking))

我希望这会有所帮助

1 个答案:

答案 0 :(得分:2)

也许首先使用已记录的对象ThreadPoolExecutorThreadPool是未记录的语言功能。

文档提供了一些最小的示例来帮助您入门。对于您的示例,请尝试以下构造:

from concurrent.futures import ThreadPoolExecutor, as_completed

values_to_test = a()
result_container = []

with ThreadPoolExecutor(max_workers=2) as executor:  # set `max_workers` as appropriate
    pool = {executor.submit(check, val, tries=0): val for val in values_to_test}

    for future in as_completed(pool):
        try:
            result_container.append(future.result())
        except:
            pass  # handle exceptions here

如果使用map方法进行设置,则不能将0作为参数传递,因为它不是可迭代的;请参见方法signature