python - 如何在Python中同一对象的另一个线程中生成一个线程?

标签 python multithreading

我正在使用加载了 Cygwin 的普通 Python 2.7

我希望能够生成一个调用顶级函数的线程子类,并且顶级函数生成调用子级函数的单独线程。这是伪代码

import threading

#!/usr/bin/python
import threading

class Server(threading.Thread):
    def __init__(self, threadID, target):
        self.__threadID = threadID
        self.__target = target
        threading.Thread.__init__(self)

    # Function called when the thread's start() function is called
    def run(self):
        self.target()
        pass

    # This is the top level function called by other objects
    def reboot(self):
        # I want this function to spawn two threads
        # - First thread calls the __powerDown() function
        # - Secod thread calls the __powerUp() function, and pends
        #   until __powerDown() thread finishes
        pass

    def __powerDown(self):
        # What to put here?
        pass

    def __powerUp(self):
        # What to put here?
        pass

    __threadID = ''
    __target = None


# Code calling above code
server = Server(123, reboot) # Will this work?

最佳答案

类似这样的吗?

import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down

关于python - 如何在Python中同一对象的另一个线程中生成一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18989472/

相关文章:

python - 实现类似 C 的断言

python - Azure Bing 图像搜索客户端抛出找不到资源的错误

javascript - 异步实际上是如何工作的......?

c++ - 并发访问 QTcpSocket 对象

Java Swing + 线程

python - 不明白这个 "object not callable"错误

python - 为什么空格会影响相等字符串的身份比较?

java - 如何使 ScheduledExecutorService 在其计划任务被取消时自动终止

Python Pandas - 计算总均值,按字段分组,然后计算分组均值并追加

java - 几个Runnable完成后的返回值