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

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

本文介绍如何利用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 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。