python 中的多线程:并行处理问题
Multi threading in python : issue with parallel processing
我正在尝试创建一个无限期侦听并提供最新信息的本地服务器。服务器运行另一个 while 循环,每隔一小时获取一次最新信息。我尝试过多线程方法,其中一个线程是一个套接字服务器(无限期运行),另一个线程(无限期地运行睡眠)将最新信息更新到全局 variable.The 全局变量然后由服务器访问和发送给它的客户。但是我看到一次只有一个线程在工作,而另一个线程根本没有启动。以下是代码。 (请注意,每次发出客户端请求时都不需要调用 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()
您将调用 runServer()
的结果作为参数传递,而不是函数 本身。所以下一行(线程)永远不会被处理。将函数作为参数传递时删除括号
th1 = threading.Thread(target=runServer)
th2 = threading.Thread(target=getInfo)
您的代码中还有很多其他注释,但这会让您继续前进。
我正在尝试创建一个无限期侦听并提供最新信息的本地服务器。服务器运行另一个 while 循环,每隔一小时获取一次最新信息。我尝试过多线程方法,其中一个线程是一个套接字服务器(无限期运行),另一个线程(无限期地运行睡眠)将最新信息更新到全局 variable.The 全局变量然后由服务器访问和发送给它的客户。但是我看到一次只有一个线程在工作,而另一个线程根本没有启动。以下是代码。 (请注意,每次发出客户端请求时都不需要调用 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()
您将调用 runServer()
的结果作为参数传递,而不是函数 本身。所以下一行(线程)永远不会被处理。将函数作为参数传递时删除括号
th1 = threading.Thread(target=runServer)
th2 = threading.Thread(target=getInfo)
您的代码中还有很多其他注释,但这会让您继续前进。