我正在Python 2.x中编写更新应用程序。我有一个线程(ticket_server)坐在longpoll模式的数据库(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所以这些问题让我的大脑陷入了一段时间。
答案 0 :(得分:3)
程序的主线程是一个线程;产生线程的唯一方法是从另一个线程。
当然,您需要确保阻塞线程在等待时释放GIL,否则其他Python线程将无法运行。所有成熟的Python数据库绑定都会这样做,但我从来没有听说过couchdb。