简体   繁体   English

主线程卡在Python多线程中

[英]Main thread stuck in Python Multithreading

I have 2 simple functions: 我有2个简单的功能:

def run(self):
    # Make 20 instances of clients and start those
    for i in xrange(0,20):
        t = threading.Thread(target = self.run_clients_in_seperate_threads())
        t.start()

and

def run_clients_in_seperate_threads(self):
    print 'inside run_clients_in_seperate_threads'
    client_id = self.generate_client_id()
    cl = Client(client_id)
    cl.start()

Here, the last line: cl.start() is an infinite loop. 在这里,最后一行: cl.start()是一个无限循环。

I was thinking that the main thread will become free after starting the child threads, and hence will spawn 20 threads in total. 我以为启动子线程后主线程将变为空闲,因此将产生总共20个线程。 But it seems that the main thread waits after starting the 1st thread. 但是似乎主线程在启动第一个线程之后等待。

Can someone please explain what I'm doing wrong ? 有人可以解释我在做什么错吗?

Use target = self.run_clients_in_seperate_threads and pass self to the args parameter . 使用target = self.run_clients_in_seperate_threads并将self传递给args参数。 The way you way you do it you invoke the method in the main thread and end up with the infinite loop there : self.run_clients_in_seperate_threads != self.run_clients_in_seperate_threads() 这样做的方式是在主线程中调用该方法,并在那里出现无限循环: self.run_clients_in_seperate_threads != self.run_clients_in_seperate_threads()

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

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