Python多线程实现同时执行两个while循环的操作

竹里
竹里
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍如何利用Python的threading模块实现两个while True循环的同时执行。通过创建独立线程分别处理音乐播放和视频播放任务,演示了多线程在并行执行耗时操作中的应用。此外,文章还补充了使用zip函数遍历多个列表的技巧,帮助开发者掌握Python并发编程的基础知识。

Python多线程实现双while循环并行执行

若需在同一进程中并行运行两个无限循环(while True),可借助Python标准库中的threading模块来创建和管理多线程。

以下是实现该功能的完整代码示例。


#coding=gbk
from time import sleep, ctime 
import threading

def muisc(func):
  while True:
    print 'Start playing: %s! %s' %(func,ctime())
    sleep(2)
 
def move(func):
  while True:
    print 'Start playing: %s! %s' %(func,ctime())
    sleep(5)

def player(name):
  r = name.split('.')[1]
  if r == 'mp3':
    muisc(name)
  else:
    if r == 'mp4':
      move(name)
    else:
      print 'error: The format is not recognized!'

list = ['爱情买卖.mp3','阿凡达.mp4']

threads = []
files = range(len(list))

#创建线程
for i in files:
  t = threading.Thread(target=player,args=(list[i],))
  threads.append(t)

if __name__ == '__main__':
  #启动线程
  for i in files:
    threads[i].start()
  for i in files:
    threads[i].join()

  #主线程
  print 'end:%s' %ctime()

运行上述代码后的实际输出效果如下。

利用zip函数并行遍历多个列表

补充知识点:在Python中如何在一个for循环内同时遍历两个列表。

利用Python内置的zip()函数可以便捷地并行遍历两个列表,具体代码实现如下。


>>> list1 = ['a', 'b', 'c', 'd']
>>> list2 = ['apple', 'boy', 'cat', 'dog']
>>> for x, y in zip(list1, list2):
    print(x, 'is', y)

# 输出
a is apple
b is boy
c is cat
d is dog

以上就是本文关于Python多线程实现双while循环并行执行的全部内容,希望能为读者提供有价值的参考,并欢迎大家继续支持本站获取更多技术分享。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表