如何线程化这些函数?

2024-09-30 10:32:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python编写一个警报,它有6个需要多线程处理的函数。其中5个是警报,其中一个显示时间。每当选择菜单选项和警报响起时,线程都需要启动和停止。显示线程是唯一一个一直运行到程序停止的线程。我当前的报警代码如下所示(为了清晰起见,我删除了很多代码)

class TAlarm1 (threading.Thread):
    def Alarm1():
        while True:
            #code which keeps running until the time is equal to the input given (expected to thread)

                            
thread1 = threading.Thread(target=TAlarm1)
thread1.start()

            
def AlarmSelector():
    print("Select an Alarm") #5 alarms will be added however each one accomplishes the same task. all of them need to run simultaneously
    choice = int(input())
    if choice == 1:
        ala = TAlarm1()
        ala.Alarm1()
    if choice == 6:
        DisplayTime() #goes back to displaying time 
     

每当我运行此代码时,程序都不会显示任何错误,但它不会在TAlarm1()中运行代码。 我怎样才能解决这个问题


Tags: theto代码程序inputtimedef警报
3条回答

在Python中实现线程代码有两种基本方法。你似乎每个都有一半

第一个实现模型是将要在线程中运行的逻辑放入函数中,然后在创建threading.Thread实例时将该函数作为target参数传递:

import threading
import time

def worker(n):
    for i in range(n):
        print(i)
        time.sleep(0.5)

my_thread = threading.Thread(target=worker, args=(10,))
my_thread.start()

# do other stuff in the main thread, if desired

my_thread.join()

另一种实现方法是将threading.Thread子类化,并将要运行的代码放在run方法(或从run调用的其他方法)内的线程中。如果您的线程代码具有某些复杂的状态,并且希望在线程运行时能够使用其他方法来操纵该状态,则这一点尤其有用:

class MyThread(threading.Thread):
    def __init__(self, n):
        super().__init__()
        self.n = n
        self.unpaused = threading.Event()
        self.unpaused.set() # we start unpaused

    def run(self):
        for i in range(self.n):
            self.unpaused.wait() # block if we're paused
            print(i)
            time.sleep(0.5)

    def pause(self):
        self.unpaused.clear()

    def unpause(self):
        self.unpaused.set()

my_thread = MyThread(10)
my_thread.start()

# an example of inter-thread communication, we pause and unpause our thread using its methods
time.sleep(2)
my_thread.pause()
time.sleep(2)
my_thread.unpause()

my_thread.join()

虽然我不清楚你的意图。下面是如何在线程的run方法被覆盖的情况下对其进行子类化,并有条件地启动它

import threading
class TAlarm1 (threading.Thread):
    def run(self):
        n =4
        while True:
            #code which keeps running until the time is equal to the input given (expected to thread)
            print(n,end=' | ')
            n -= 1
            if n < 0:
                break
        print()

t1 = TAlarm1()
if True:
    t1.start()

线程只能启动一次,因此每次需要运行时都必须创建一个新线程

>>> t = TAlarm1() 
>>> t.start()
4 | 3 | 2 | 1 | 0 | 
>>> t.start()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python38\lib\threading.py", line 848, in start
    raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once
>>> t = TAlarm1()
>>> t.start()
4 | 3 | 2 | 1 | 0 | 
>>>

Threadtarget参数采用可调用的。类是可调用的,但调用它只会创建类的实例。改为传递一个函数

import threading

def Alarm1():
    print('Alarm1 called')
                            
thread1 = threading.Thread(target=Alarm1)
thread1.start()

相关问题 更多 >

    热门问题