请教一个关于多线程的问题

在主线程设置了一份定时器Timer,定时器倒计时结束后调用一个函数,我希望这个函数开始以后能直接执行到底,所以在函数开头加上了threading.current_thread().join(),但是似乎阻塞在这句代码不往下执行了,对于多线程我掌握的还不够多,希望大家能给点建议。

定时器代码
请教一个关于多线程的问题

Jason990420
最佳答案

以下是Timer的定义

  1. 没有定义暂停(pasue) 以及恢复(resume)的方法
  2. runwait(interval), 再直接执行函数, 是没去停下来的.
  3. start会调用run
class Timer(Thread):

    def __init__(self, interval, function, args=None, kwargs=None):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args if args is not None else []
        self.kwargs = kwargs if kwargs is not None else {}
        self.finished = Event()

    def cancel(self):
        """Stop the timer if it hasn't finished yet."""
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()

所以, 如果想要pauseresume, 得自己定义, 使用旗标来作控制, 比如以下的方式, 这例子仅用于Thread, Thread并没有wait(interval) , 不能直接套用在Timer

import threading
import time

class Job(threading.Thread):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__flag = threading.Event() # Suspend the thread's identity
        self.__flag.set() # set to True
        self.__running = threading.Event() # Stop the thread's identity
        self.__running.set() # Set Running to True

    def run(self):
        while self.__running.isset(): # returns immediately when false,
            self.__flag.wait () # blocking until the internal identity
            time.sleep(1) # bit is true to return

    def pause(self):
        self.__flag.clear() # False to allow threads to block

    def resume(self):
        self.__flag.set() # True to allow thread to stop blocking

    def stop (self):
        self.__flag.set() # Restores a thread from a paused state.
        self.__running.clear() # How to have paused set to False
4年前 评论
讨论数量: 3
Jason990420

join 将阻塞调用线程, 等待被调用的线程终止, 直到join()被调用方法的线程终止.

For example, no join

from time import sleep
from threading import Timer

def f():
    global i
    if ending:
        return
    i+=1
    print(f'{i} second(s) passed')
    Timer(1, f).start()

ending = False  # Flag to stop thread f
i = 0
t1 = Timer(1, f)
t1.start()

sleep(10)       # Wait 10 seconds to stop thread f, you can do something else
ending = True   # then set ending to True to stop thread
4年前 评论

@Jason990420
感谢回复!
我现在已经明白join()的意思,阻塞的是当前执行join()的线程,一直到join()方法前的那个线程执行结束。
不过我还有一个问题,如果希望一个线程执行到某一处时开始独占CPU,不受其它线程抢占,直到执行结束,不知道有没有方法?

4年前 评论
Jason990420

以下是Timer的定义

  1. 没有定义暂停(pasue) 以及恢复(resume)的方法
  2. runwait(interval), 再直接执行函数, 是没去停下来的.
  3. start会调用run
class Timer(Thread):

    def __init__(self, interval, function, args=None, kwargs=None):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args if args is not None else []
        self.kwargs = kwargs if kwargs is not None else {}
        self.finished = Event()

    def cancel(self):
        """Stop the timer if it hasn't finished yet."""
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()

所以, 如果想要pauseresume, 得自己定义, 使用旗标来作控制, 比如以下的方式, 这例子仅用于Thread, Thread并没有wait(interval) , 不能直接套用在Timer

import threading
import time

class Job(threading.Thread):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__flag = threading.Event() # Suspend the thread's identity
        self.__flag.set() # set to True
        self.__running = threading.Event() # Stop the thread's identity
        self.__running.set() # Set Running to True

    def run(self):
        while self.__running.isset(): # returns immediately when false,
            self.__flag.wait () # blocking until the internal identity
            time.sleep(1) # bit is true to return

    def pause(self):
        self.__flag.clear() # False to allow threads to block

    def resume(self):
        self.__flag.set() # True to allow thread to stop blocking

    def stop (self):
        self.__flag.set() # Restores a thread from a paused state.
        self.__running.clear() # How to have paused set to False
4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!