【发布时间】:2010-10-10 23:49:36
【问题描述】:
我正在用 Python 2.x 编写一个更新应用程序。我有一个线程(ticket_server)以长轮询模式坐在数据库(CouchDB)url 上。更新请求从外部应用程序转储到此数据库中。当发生变化时,ticket_server 会触发一个工作线程(update_manager)。繁重的工作在这个 update_manager 线程中完成。将执行 telnet 连接和 ftp 上传。所以最重要的是不要中断这个过程。
我的问题是,从 ticket_server 线程中生成 update_manager 线程是否安全?
另一种选择可能是将请求放入队列,并让另一个函数等待票证进入队列,然后将请求传递给 update_manager 线程。但是,我宁愿保持简单(我假设 ticket_server 产生 update_manager 很简单),直到我有理由扩展。
# Here is the heavy lifter
class Update_Manager(threading.Thread):
def __init__(self)
threading.Thread.__init__(self, ticket, telnet_ip, ftp_ip)
self.ticket = ticket
self.telnet_ip = telnet_ip
self.ftp_ip = ftp_ip
def run(self):
# This will be a very lengthy process.
self.do_some_telnet()
self.do_some_ftp()
def do_some_telnet(self)
...
def do_some_ftp(self)
...
# This guy just passes work orders off to Update_Manager
class Ticket_Server(threading.Thread):
def __init__(self)
threading.Thread.__init__(self, database_ip)
self.database_ip
def run(self):
# This function call will block this thread only.
ticket = self.get_ticket(database_ip)
# Here is where I question what to do.
# Should I 1) call the Update thread right from here...
up_man = Update_Manager(ticket)
up_man.start
# Or should I 2) put the ticket into a queue and let some other function
# not in this thread fire the Update_Manager.
def get_ticket()
# This function will 'wait' for a ticket to get posted.
# for those familiar with couchdb:
url = 'http://' + database_ip:port + '/_changes?feed=longpoll&since=' + update_seq
response = urllib2.urlopen(url)
这只是询问哪种方法更安全/更有效/更pythonic的大量代码 我只有几个月的时间使用 python,所以这些问题让我的大脑陷入了一段时间的循环。
【问题讨论】:
标签: python multithreading