简体   繁体   中英

How to make Python do a loop for all items in list at the same time?

I have a list and I'm trying to do a loop for each item in the list, all at the same time.

I've tried using this code:

thelist = ['first', 'second', 'third']

def loop():
    while True:
        for x in thelist:
            x = str(x)
            time.sleep(5)
            do_stuff_that_includes_x()

But it does the stuff in the loop one by one as sorted in thelist .

And I want it to do the stuff for all items in thelist at the same time .

Thanks in advance.

As has been noted in the comments by vossad01, your code has a 5 seconds delay inside your loop. This will cause a five second delay between any two items on the list. If you remove the 5 second delay, your messages will be sent to all rooms in the list near-instantaneous.

thelist = ['first', 'second', 'third']

def loop():
    while True:
        for x in thelist:
            x = str(x)
            do_stuff_that_includes_x() 

        time.sleep(5)

I think you need multi-processing:

import time

def work(x):
    x = str(x)
    time.sleep(5)
    print x
#   do_stuff_that_includes_x()

thelist = ['first', 'second', 'third']
from multiprocessing import Pool
p = Pool( len( thelist ) )
p.map( work, thelist )

First, multithreaded parallelization does not tend to yield performance increases because of the Global Interpreter Lock (GIL). Thus, if you are doing this for performance reasons you will need to look at the multiprocessing module. See how do I parallelize a simple python loop? for an example of using the map member of of a process pool to accomplish this.

Side notes: It is bad form to re-assign the iterating variable (x). Additionally, since you want parallel execution it will be easiest if you can make do_stuff_that_includes_x() parametrized on x.

使用*运算符一次解压缩整个列表

do_stuff_that_includes_x(*x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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