相关疑难解决方法(0)

覆盖python threading.Thread.run()

鉴于Python文档Thread.run():

您可以在子类中覆盖此方法.标准的run()方法调用传递给对象构造函数的可调用对象作为目标参数(如果有),分别使用args和kwargs参数中的顺序和关键字参数.

我构造了以下代码:

class DestinationThread(threading.Thread):
    def run(self, name, config):
        print 'In thread'

thread = DestinationThread(args = (destination_name, destination_config))
thread.start()
Run Code Online (Sandbox Code Playgroud)

但是当我执行它时,我收到以下错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner
    self.run()
TypeError: run() takes exactly 3 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)

我似乎错过了一些明显的东西,但我看到的各种例子都与这种方法有关.最终我试图将字符串和字典传递给线程,如果构造函数不是正确的方法,而是在启动线程之前创建一个新函数来设置值,我对此持开放态度.

有关如何最好地完成此任务的任何建议?

python multithreading

37
推荐指数
4
解决办法
6万
查看次数

Python - 如何实现“可停止”线程?

这里发布一个解决方案来创建一个可停止的线程。但是,我在理解如何实施此解决方案时遇到了一些问题。

使用代码...

import threading

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()
Run Code Online (Sandbox Code Playgroud)

如何创建一个线程来运行每 1 秒向终端打印一次“Hello”的函数。5 秒后,我使用 .stop() 停止循环函数/线程。

我再次在理解如何实现这个停止解决方案时遇到了麻烦,这是我目前所拥有的。

import threading
import time

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def …
Run Code Online (Sandbox Code Playgroud)

multithreading class python-3.x

3
推荐指数
1
解决办法
3995
查看次数

标签 统计

multithreading ×2

class ×1

python ×1

python-3.x ×1