多线程不是 运行 任务

multithreading not running task

所以我整天都在摆弄这个多线程,但似乎可以让它工作。它也在 Python 3 中。

该程序正在尝试生成 5 个单词的列表 1000 次并使用多线程来提高速度。

我已经将代码更改为很多我一直在网上搜索但没有结果的不同方法。

根据我目前的情况,它将 运行 没有任何问题,但不会打印任何文字。

任何人都可以看一看。

import random
from threading import Thread

word_file = "words.txt"


def gen():
    Words = open(word_file).read().splitlines() #retreiving and sorting word file
    seed = random.randrange(0,2048) #amount of words to choose from in list

    for x in range(0, 1000):
        print(random.choices(Words, k=5)) #print the words

def main():
    t1 = Thread(target=gen)
    t2 = Thread(target=gen)
    t3 = Thread(target=gen)
    t4 = Thread(target=gen)
    t1.start()
    t2.start()
    t3.start()
    t4.start()

print("completed")

非常简单:您的代码没有调用任何函数,只是构建它们并让它们独立。

只需在 print("completed") 之前添加 main(),以便代码调用该函数。

注1:为什么在循环里面一遍又一遍的读取文本文件,为什么还要手动打开呢?通过以下方式自动关闭它:

with open(word_file, "r") as f:
    Words = f.read().splitlines()

代码在 gen().

之前

注2:seed在做什么?您定义了它但没有在任何地方使用它。

注3:发帖前请检查缩进。