繁体   English   中英

Python,一个线程产生另一个线程是否合适

[英]Python, is it proper for one thread to spawn another

我正在用Python 2.x编写更新应用程序。 我在longpoll模式下有一个线程(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 Im仅使用python才几个月,所以这些问题使我的大脑陷入了while循环。

程序的主线程线程。 产生线程的唯一方法是来自另一个线程。

当然,您需要确保阻塞线程在等待时释放GIL,否则其他Python线程将无法运行。 所有成熟的Python数据库绑定都可以做到这一点,但是我从未听说过ouchdb。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM