如何在Python中实现worker / keepalive线程组合?

时间:2012-04-21 12:46:29

标签: python multithreading

线程融化了我的大脑。我已经看到了实现worker + keepalive模型的几种不同方法,但很难找出最佳方法。这是代码的简化版本:

def start_thread(function):
    t = Thread(target=function)
    t.setDaemon(True)
    t.start()

def worker:
    run = True
    start_thread(keepalive_fn)

    msg = recv() #blocking
    while msg is not None and run:
        process(msg)
        try:
            msg = recv()
        except:
            if run:
                reconnect()
            break
    else:
        if run:
            reconnect()

def keepalive_fn():
    while run:
        try:
            send('hb')
        except:
            close_connection()
            break
        sleep(heartbeat)

def connect():
    open_connection()
    start_thread(worker)

def reconnect():
    close_connection()
    connect()

connect()

这会像宣传的一样工作吗?有没有更好的办法?请注意,调用close_connection()时没有损坏的msg,因为recv()已经处理了这种情况。

1 个答案:

答案 0 :(得分:0)

通常的方法是在recv()调用上启用超时,方法是在套接字上设置超时或使用select / epoll()调用并使用它来发出轮询并将其计时。伪:

bool timedOutOnce=false;
while(true){
  result=recv();
  if(result<>timeout){
       timedOutOnce=false;
       if (message<>serverPollReply) processMsg();
  }
  else
    {
      if(timedOutOnce){
         // server has not replied!!
         closeSocket;
         return(NoReplyFromServer);
      }
      else
        {
           // nothing received for a while, so..
           send(serverPollMessage);
           timedOutOnce=true;
        }
    }

}