python threading method stuck

落花浮王杯 提交于 2021-02-17 05:27:10

问题


I have a class MyClass which creates 7 threads when it is initialized. One thread is a TCPServer, and the other six are objects of MyClass which the TCPServer uses to process requests.

My intention is to create method which can run in the background of MyClass and maintain the 6 threads. The 6 threads correspond to 2 distributed objects obj1 and obj2 replicated with an implementation of Raft called PySyncObj. There are three threads per object.

Each cluster of objects obj_1_cluster and obj_2_cluster has a leader, which the server must keep track of, because all changes to the object must be sent only to the leader.

class MyClass(object):

def __init__(self):

    self.server = TCPServer()

    self.obj_1_cluster = self.init_cluster(Class_1['bindings'], Class_1)
    self.server.obj1 = self.get_leader(obj_1_cluster)

    self.obj_2_cluster = self.init_cluster(obj_2['bindings'], Class_2)
    self.server.obj2 = self.get_leader(obj_2_cluster)


    # Create Daemon process for keeping leader current.
    self.obj1_leader_daemon = Thread(target = self.__obj1_leader_daemon())
    self.obj1_leader_daemon.setDaemon(True)
    self.obj1_leader_daemon.start()

    self.obj2_leader_deamon = Thread(target = self.__obj2_leader_daemon())
    self.obj2_leader_deamon.setDaemon(True)
    self.obj2_leader_deamon.start()

def __obj1_leader_daemon(self):
    while True:
        print("Running obj1 daemon")
        if self.server.obj1._isLeader():
            pass
        else:
            self.server.obj1 = self.get_leader(self.obj1)

def __obj2_leader_daemon(self):
    while True:
        print("running obj2 daemon")
        if self.server.obj2._isLeader():
            pass
        else:
            self.server.obj2 = self.get_leader(self.obj2)

When I run this code, the only output I see is...

Running obj1 daemon
Running obj1 daemon
Running obj1 daemon
...

until I kill the process with ctrl-C.

Is there a way to change this so that these two processes can run with their own thread- busily checking the state of the objects in case they need to change them? I've read a lot about threading and I don't see why this isn't currently working the way I think it should.

Environment: I'm running python 2.7.14 on MacOS 10.13.3.


回答1:


__init__ gets stuck at

self.obj1_leader_daemon = Thread(target = self.__obj1_leader_daemon())

The thread target should be the name of the function to run, but you've called the function instead. self.__obj1_leader_daemon() is an infinite loop so it never returns, nothing is assigned to target and no thread is ever created. Your main thread hangs running the daemon code.

Just remove the cowboy legs

self.obj1_leader_daemon = Thread(target = self.__obj1_leader_daemon)

... and do the same for the other thread.



来源:https://stackoverflow.com/questions/49101624/python-threading-method-stuck

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!