具有相同条件的多个while循环会依次还是同时启动?

时间:2018-12-03 18:34:39

标签: python while-loop

假设我有多个基于同一个变量的while循环,例如

#loop 1
count = 0
while count < len(list): #where list is non-empty
    do stuff
    count = count + 1
delete some things from list
count = 0

#loop 2
while count < len(list): #where list is still non-empty but shorter than before
    do other stuff
    count = count + 1
delete more things from list
count = 0

#loop 3
while 0 < len(list): #where list is less than before but still nonempty
    while count < len(list): #nested within above while loop
        do even more stuff
        count = count + 1
    delete more items of the list
    count = 0
#list is now empty

这3个while循环会同时触发吗?还是一次启动一个?

3 个答案:

答案 0 :(得分:0)

程序是指令列表。

它们从上到下执行。

因此,答案为,它们将不会同时触发。


例如这里会发生什么?

import time
print('one')
time.sleep(1)
print('two')
time.sleep(1)
print('three')

答案 1 :(得分:0)

由于您不是多线程/处理程序,因此它是从程序顶部到底部的逐行执行。因此,它将顺序运行,而不是并行运行。

答案 2 :(得分:0)

这是一个测试用例:

items = [1,2,3,4,5,6,7,8,9]

count = 0
while items:
    print(items.pop(0))
    count += 1
    if count == 3:
        break

print("new while")
while items:
    print(items.pop(0))
    count += 1
    if count == 6:
        break

print("last while")
while items:
    print(items.pop(0))
    count += 1

由于Python的GIL,许多项(例如列表)也可以并发操作,而无需将它们分割:

import threading, time
items = [1,2,3,4,5,6,7,8,9]

def stuff(x, count_limit):
    t = threading.current_thread()
    count = 0
    while items:
        print(t.name + ": " + str(items.pop(0)) + " count: " + str(count) + "\n", end = "")
        count += 1
        if count_limit:
            if count == count_limit:
                break

threads = []

counts = [3,6,False]
for x, count in enumerate(counts):
    t = threading.Thread(target = stuff, args = (items, count,))
    t.name = "Thread " + str(x)
    threads.append(t)

对于线程中的线程:     thread.start()

对于线程中的线程:     thread.join()