欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python的多线程与多进程编程示例

程序员文章站 2023-09-17 23:23:27
使用示例:多进程:from multiprocessing import Processfrom os import getpidfrom random import randintfrom time import time, sleepdef download_task(filename): print('启动下载进程,进程号[%d].' % getpid()) print('开始下载%s...' % filename) time_to_download = ran...

使用示例:

多进程:

# -*- coding: utf-8 -*-
"""
Python多进程的简单使用
"""
from multiprocessing import Process
from os import getpid
from random import randint
from time import time, sleep


def download_task(filename):
    print('启动下载进程,进程号[%d].' % getpid())
    print('开始下载%s...' % filename)
    time_to_download = randint(5, 10)
    sleep(time_to_download)
    print('%s下载完成! 耗费了%d秒' % (filename, time_to_download))


def main():
    start = time()
    p1 = Process(target=download_task, args=('Python从入门到住院.pdf', ))
    p1.start()
    p2 = Process(target=download_task, args=('Peking Hot.avi', ))
    p2.start()
    p1.join()  # 等待进程1执行完毕,再执行下一步
    p2.join()  # 等待进程2执行完毕,再执行下一步
    end = time()
    print('总共耗费了%.2f秒.' % (end - start))


if __name__ == '__main__':
    main()

多线程:

# -*- coding: utf-8 -*-
"""
Python的多线程简单使用
"""
from random import randint
from threading import Thread
from time import time, sleep


def download(filename):
    print('开始下载%s...' % filename)
    time_to_download = randint(5, 10)
    sleep(time_to_download)
    print('%s下载完成! 耗费了%d秒' % (filename, time_to_download))


def main():
    start = time()
    t1 = Thread(target=download, args=('Python从入门到住院.pdf',))
    t1.start()
    t2 = Thread(target=download, args=('Peking Hot.avi',))
    t2.start()
    t1.join()  # 等待线程1执行完毕,再执行下一步
    t2.join()  # 等待线程2执行完毕,再执行下一步
    end = time()
    print('总共耗费了%.3f秒' % (end - start))


if __name__ == '__main__':
    main()

或者通过继承Thread类的方式来创建自定义的线程类,然后再创建线程对象并启动线程:

from random import randint
from threading import Thread
from time import time, sleep


class DownloadTask(Thread):

    def __init__(self, filename):
        super().__init__()
        self._filename = filename

    def run(self):
        print('开始下载%s...' % self._filename)
        time_to_download = randint(5, 10)
        sleep(time_to_download)
        print('%s下载完成! 耗费了%d秒' % (self._filename, time_to_download))


def main():
    start = time()
    t1 = DownloadTask('Python从入门到住院.pdf')
    t1.start()
    t2 = DownloadTask('Peking Hot.avi')
    t2.start()
    t1.join()  # 等待线程1执行完毕,再执行下一步
    t2.join()  # 等待线程2执行完毕,再执行下一步
    end = time()
    print('总共耗费了%.2f秒.' % (end - start))


if __name__ == '__main__':
    main()

注意:
在平时的使用中,就不需要调用join()来等待进程和线程的执行完毕了,不然会导致主进程和主线程的阻塞。

本文地址:https://blog.csdn.net/guanmaoning/article/details/107372013