Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python置换线程_Python_Multithreading_Permutation - Fatal编程技术网

Python置换线程

Python置换线程,python,multithreading,permutation,Python,Multithreading,Permutation,我已经用python中的itertools.permutations函数生成了置换。问题是结果非常大,我想用多个线程来完成它,但不知道如何实现这一点,这是我到目前为止得到的结果: perms = itertools.permutations('1234', r=4) #I would like to iterate through 'perms' with multiple threads for perm in perms: print perm Python的模块使在线程之间分割

我已经用python中的itertools.permutations函数生成了置换。问题是结果非常大,我想用多个线程来完成它,但不知道如何实现这一点,这是我到目前为止得到的结果:

perms = itertools.permutations('1234', r=4)

#I would like to iterate through 'perms' with multiple threads
for perm in perms:
    print perm
Python的模块使在线程之间分割工作变得容易。在本例中,将使用4个线程,但您可以修改它以满足您的需要

from concurrent import futures

def thread_process(perm):
    #do something

with futures.ThreadPoolExecutor(max_workers=4) as executor:
    for perm in perms:
        executor.submit(thread_process, perm)

假设你的处理函数是你想要做的f(x)

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)   # start 4 worker processes
    perms = itertools.permutations('1234', r=4)
    for r in pool.map(f, perms):
        print (r)  

事实上,使用线程不会并行执行进程,除非它是IO绑定的。如果它是CPU限制的,并且您有一个四核,那么它就是最好的选择。如果您没有多核,并且它受CPU限制,那么我担心将其并行化不会改善您当前的状况。

如果您想使用置换生成器中的项进行CPU密集型工作,您可能希望使用进程而不是线程。CPython的全局解释器锁(GIL)使多线程在执行CPU限制的工作时具有有限的价值

相反,请使用模块的
类,如下所示:

import multiprocessing
import itertools

def do_stuff(perm):
    # whatever
    return list(reversed(perm))

if __name__ == "__main__":
    with multiprocessing.Pool() as pool: # default is optimal number of processes
        results = pool.map(do_stuff, itertools.permutations('1234', r=4))

        # do stuff with results
请注意,如果您将迭代
结果
(而不是将其作为列表进行处理),则可以使用
imap
而不是
map
来获取迭代器,您可以使用该迭代器处理从辅助进程生成的结果。如果返回项目的顺序无关紧要,您可以使用
imap\u unordered
来(我认为)节省一点内存


Windows上需要
如果名称为“\uuuuu main\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu.

在线程之间拆分perm数的索引,然后使用从每个线程中的索引生成perm,而不是生成所有perm并在线程之间拆分它们。

您希望如何在线程之间拆分数据?为什么要使用多线程?我想将其平均分割:如果“perms”包含1'000'000个条目,而我有4个线程,则每个线程应处理250'000个条目;如果我只使用一个线程,则需要大约10分钟来浏览整个条目,因此我想使用多个线程。您的进程是IO绑定的还是CPU绑定的?您使用的是CPython还是jython之类的其他版本,pypy?我必须遍历这些条目,对它们执行一些操作,然后将它们写入一个文件。我对条目执行的操作应该由多个线程完成使用线程的问题是,它不会执行OP想要的操作,因为它不会并行执行GIL。我不明白他在哪里说的“使用多个线程”是什么意思-他可以做任何事情,从执行另一个进程到进行阻止线程的套接字/文件调用。在这些情况下,GIL不会造成问题。我同意这当然取决于他想做什么。