在并发中使用此功能不起作用

问题描述 投票:0回答:1

我正在使用concurrent.futures.ProcessPoolExecutor()构造一组数组以使其更快。但是由于某些原因,该功能在de ProcessPoolExecutor()内部无法正常工作。

我的代码如下:

def func(h):
    l = 20
    A = np.zeros((2**8,2**8))
    i = 2**12
    for x in range(0,2**l):
        for y in range(0,l):
            k = (y+1)%l
            print(x//i,x,y)
            if check(x,y) == 0:
                A[x//i,x//i] += -const
            else:
                A[x//i,x//i] += const
            if check(x,y) == check(x,k):
                A[x//i,x//i] += -const_2
            else:
                A[x//i,x//i] += const_3
                b = bitflip(x,y)
                c = bitflip(b,k)
                A[x//i,c//i] += -const_4
    print(A)

t1 = time.perf_counter()
list_t = [16,13,12]
with concurrent.futures.ProcessPoolExecutor() as executor:
    executor.map(func,list_t)


t2 = time.perf_counter()

print(f'Finished in {t2-t1} seconds')

输出就像它在第一个循环中只输入一次:

0 0 0
0 0 0
0 0 0
Finished in 0.1943432055413723 seconds

但是如果我注释该部分给数组A的赋值,它将打印出完整的循环

python multiprocessing concurrent.futures
1个回答
0
投票

问题出在您身上func(h),检查错误。该代码正在按预期并行执行。

check()和bitflip()来自何处?

import time
import concurrent.futures
import numpy as np
from random import randrange
import time

def func(h):
    time.sleep(randrange(5))
    l = 20
    A = np.zeros((2**8,2**8))
    i = 2**12
    for x in range(0,2**l):
        for y in range(0,l):
            k = (y+1)%l
            print(x//i,x,y)
            if check(x,y) == 0:
                A[x//i,x//i] += -const
            else:
                A[x//i,x//i] += const
            if check(x,y) == check(x,k):
                A[x//i,x//i] += -const_2
            else:
                A[x//i,x//i] += const_3
                b = bitflip(x,y)
                c = bitflip(b,k)
                A[x//i,c//i] += -const_4
    print(A)

t1 = time.perf_counter()
list_t = [16,13,12, 15, 17]
with concurrent.futures.ProcessPoolExecutor() as executor:
    executor.map(func,list_t)


t2 = time.perf_counter()

print(f'Finished in {t2-t1} seconds')

产量

0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
Finished in 4.032956823997665 seconds
© www.soinside.com 2019 - 2024. All rights reserved.