2010-10-10 122 views
1

我正在使用Python 2.x编写更新应用程序。我有一个线程(ticket_server)在longpoll模式下坐在数据库(CouchDB)url上。更新请求从外部应用程序转储到此数据库中。当发生变化时,ticket_server会触发一个工作线程(update_manager)。繁重的工作是在这个update_manager线程中完成的。将会执行telnet连接和ftp上传。所以这个过程最重要的是不要中断。Python,是否适合一个线程产生另一个线程

我的问题是,从ticket_server线程产生update_manager线程安全吗?

另一个选项可能是将请求放入队列中,并让另一个函数等待票证进入队列,然后将请求传递给update_manager线程。但是,Id宁愿简单(我假设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) 

这仅仅是大量的代码要问哪种方法更安全/更高效/更Python 我只是在旧有蟒蛇几个月所以这些问题让我的大脑停留在一个while循环。

回答

3

程序主线程一个线程;产生一个线程的唯一方法是从另一个线程。

当然,您需要确保您的阻塞线程在等待时释放GIL,否则其他Python线程将无法运行。所有成熟的Python数据库绑定都会这样做,但我从来没有听说过couchdb。

+1

couchdb是那些新颖的“面向对象的数据库”之一。 – Arafangion 2010-10-11 01:18:12

+2

@Arafangion,或许我们应该在误导那些没有听说过couchdb的人之前检查'它不是什么'“。 – sbartell 2010-10-11 01:51:15

+0

@Glenn,我应该举几个例子来更好地说明我的问题。 – sbartell 2010-10-11 01:53:27

相关问题