python中的多线程:并行处理问题

时间:2015-07-02 20:14:58

标签: multithreading python-2.7 parallel-processing serversocket

我正在尝试创建一个无限侦听并提供最新信息的本地服务器。服务器运行另一个while循环,每隔一小时获取最新信息。我尝试过多线程方法,其中一个线程是套接字服务器(无限期运行),另一个线程(无休止地运行)将最新信息更新为全局变量。然后服务器访问全局变量并发送给它的客户。但是我发现一次只有一个线程正在工作而另一个线程根本没有开始。以下是代码。 (请注意,每次发出客户端请求时都需要调用getInfo()/ retriveInfoFromDB()来获取最新信息,因为前者是非常耗时的过程)。非常感谢任何帮助。

from socket import *
import threading
import pandas as pd
import json
import time
import datetime
import thread

#Global Info variable
info = pd.DataFrame()

def getInfo():
    global info
    while 1:
        print "Information retrieval running"
        try:
            #This will bring the required infor as pandas df
            info = retriveInfoFromDB()          
        except:
            pass
        time.sleep(3600)

def runServer():
    global info
    address = ('localhost', 6005)
    server_socket = socket(AF_INET, SOCK_DGRAM)
    server_socket.bind(address)   

    while(1):
        print "Listening"
        recv_data, addr = server_socket.recvfrom(2048)

        server_socket.sendto(info.to_json(path_or_buf = None, orient = 'records', date_format = 'epoch', double_precision = 10, force_ascii = True, date_unit = 'ms', default_handler = None), addr)

th1 = threading.Thread(target=runServer())
th2 = threading.Thread(target=getInfo())

th1.start()
th2.start()

1 个答案:

答案 0 :(得分:2)

您将调用 runServer()的结果作为参数传递,而不是函数本身。所以永远不会处理下一行(线程)。将函数作为参数传递时删除括号

th1 = threading.Thread(target=runServer)
th2 = threading.Thread(target=getInfo)

您的代码还有很多其他评论,但这可以帮助您。