Python多线程(_thread)无效

0 投票
1 回答
574 浏览
提问于 2025-04-18 15:25

首先,这里有我的两个Python文件:

sred.py:

import _thread,time

class Thread:

def __init__(self,time:int,say:str):

    self.time=time
    self.say=say


def create():
    id = _thread.get_ident() 


    for i in range(5):

        print("HALLO", id)

    return

from sred import Thread
import time,_thread

_thread.start_new_thread(Thread.create,())

第二个文件:

main.py

from sred import Thread
import time,_thread

_thread.start_new_thread(Thread.create,())

运行这个的时候,它什么都不打印出来,为什么呢?

更新:

import _thread

class Thread:


    @classmethod
    def create():
        id = _thread.get_ident() 


        for i in range(5):
            print("HALLO", id)
        return

main.py:

from sred import Thread
import time,_thread

_thread.start_new_thread(Thread().create,())

这样写对了吗,还是说还有什么问题?

1 个回答

1

这个 create 方法缺少了 self 这个参数——如果你想像现在这样调用它,它应该是一个 @classmethod。注意,你的 __init__ 方法从来没有被调用,因为你没有创建任何 Thread 对象。你可能想把它改成这样:

_thread.start_new_thread(Thread().create, ())

也就是说,先创建一个线程,然后把它的 create 方法传递过去,让新线程去执行。我不太确定发生了什么,但我怀疑有些地方出错了,导致 错误信息被隐藏了。

另外,你需要删除 for 语句后面的空格——这个空格是很重要的,它应该会让你看到一个关于意外缩进的语法错误。

编辑:

这个版本在我的机器上能运行:

import _thread

class Thread:
    def create(self):
        id = _thread.get_ident() 

        for i in range(5):
            print("HALLO", id)
        return

_thread.start_new_thread(Thread().create, ())

撰写回答