Python:线程没有任何理由停止

时间:2013-07-07 15:51:26

标签: python multithreading exception

我正在尝试创建一个哈希破解应用程序,它将检查所有行 文件包含有关字典中的所有行。虽然预先练习摇滚你 我有时间检查一个哈希到几秒钟仍然不够。这是 为什么我要将我的程序转移到多线程。但我的线程停止而没有任何异常。

import threading
import datetime

class ThreadClass(threading.Thread):
    hash_list=0
    def file_len(fname):
        with open(fname) as f:
            for i, l in enumerate(f):
                pass
        return i + 1
    list_len=file_len("list.txt")

    def run(self):
        while ThreadClass.list_len>0:
            ThreadClass.list_len=ThreadClass.list_len-1
            print str(threading.current_thread())+":"+str(ThreadClass.list_len)
for i in range(20):
    try:
        t = ThreadClass()
        t.start()
    except:
        raise

这是输出: Afther that there is only one thread printing 当我在一段时间后运行它时,只有一个线程报告。为什么? 感谢您的帮助

编辑:其中一个主题出现了一个关键错误。我不知道那是什么

1 个答案:

答案 0 :(得分:4)

由于计算哈希是CPU绑定问题,使用多线程对cPython because of the GIL无效。

如果有的话,您需要使用multiprocessing。使用Pool,您的整个代码可以简化为:

import multiprocessing

def calculate(line):
    # ... calculate the hash ...
    return (line, 'calculated_result')

pool = multiprocessing.Pool(multiprocessing.cpu_count())

with open('input.txt') as inputfile:
    result = pool.map(calculate, inputfile)

print(result)
# compare results

关于线程的问题:您同时从多个theads访问ThreadClass.list_len。 首先,您访问它并将其与0进行比较。然后再次访问它,减少它并将其存储回来,这是not thread safe 然后在打印时再次访问它。在任何这些操作之间,另一个线程可以修改该值。

为了表明这一点,我稍微修改了你的代码:

import threading
import datetime

lns = []
class ThreadClass(threading.Thread):
    hash_list=0
    list_len= 10000

    def run(self):
        while ThreadClass.list_len>0:
            ThreadClass.list_len=ThreadClass.list_len-1
            ln = ThreadClass.list_len        # copy for later use ...
            lns.append(ln)

threads = []
for i in range(20):
    t = ThreadClass()
    t.start()
    threads.append(t)

for t in threads:
    t.join()

print len(lns), len(set(lns)), min(lns)

当我跑10次时,得到的是:

13473 9999 -1
10000 10000 0
10000 10000 0
12778 10002 -2
10140 10000 0
10000 10000 0
15579 10000 -1
10866 9996 0
10000 10000 0
10164 9999 -1

所以有时似乎运行正常,但其他人有很多值已被多次添加,而list_len甚至设法变为负面。

如果你反汇编run方法,你会看到:

>>> dis.dis(ThreadClass.run)
 11           0 SETUP_LOOP              57 (to 60)
        >>    3 LOAD_GLOBAL              0 (ThreadClass)
              6 LOAD_ATTR                1 (list_len)
              9 LOAD_CONST               1 (0)
             12 COMPARE_OP               4 (>)
             15 POP_JUMP_IF_FALSE       59

 12          18 LOAD_GLOBAL              0 (ThreadClass)
             21 LOAD_ATTR                1 (list_len)
             24 LOAD_CONST               2 (1)
             27 BINARY_SUBTRACT     
             28 LOAD_GLOBAL              0 (ThreadClass)
             31 STORE_ATTR               1 (list_len)

 13          34 LOAD_GLOBAL              0 (ThreadClass)
             37 LOAD_ATTR                1 (list_len)
             40 STORE_FAST               1 (ln)

 14          43 LOAD_GLOBAL              2 (lns)
             46 LOAD_ATTR                3 (append)
             49 LOAD_FAST                1 (ln)
             52 CALL_FUNCTION            1
             55 POP_TOP             
             56 JUMP_ABSOLUTE            3
        >>   59 POP_BLOCK           
        >>   60 LOAD_CONST               0 (None)
             63 RETURN_VALUE    

简化你可以说,在任何这些行之间,另一个线程可以运行和修改某些东西。要从多个线程安全地访问值,您需要同步访问权限。

例如,使用threading.Lock代码可以像这样修改:

class ThreadClass(threading.Thread):
    # ...
    lock = threading.Lock()

    def run(self):
        while True:
            with self.lock:
                # code accessing shared variables inside lock
                if ThreadClass.list_len <= 0:
                    return
                ThreadClass.list_len -= 1
                list_len = ThreadClass.list_len   # store for later use...
            # not accessing shared state, outside of lock

我不完全确定这是导致问题的原因,但可能是,特别是如果您还在运行方法中读取输入文件。