脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - Python多线程编程全解析:基础到高级用法

Python多线程编程全解析:基础到高级用法

2024-03-27 15:56架构师老卢 Python

Python的Threading模块提供了多线程编程的基本工具。在下面,我将列举一些基础的多线程用法和一些高级用法,并提供相应的源代码,其中包含中文注释。

Python多线程编程全解析:基础到高级用法

Python中有多线程的支持。Python的threading模块提供了多线程编程的基本工具。在下面,我将列举一些基础的多线程用法和一些高级用法,并提供相应的源代码,其中包含中文注释。

基础用法:

创建和启动线程

import threading
import time

# 定义一个简单的线程类
class MyThread(threading.Thread):
    def run(self):
        for _ in range(5):
            print(threading.current_thread().name, "is running")
            time.sleep(1)

# 创建两个线程实例
thread1 = MyThread(name="Thread-1")
thread2 = MyThread(name="Thread-2")

# 启动线程
thread1.start()
thread2.start()

# 主线程等待所有子线程结束
thread1.join()
thread2.join()

print("Main thread exiting")

线程同步 - 使用锁

import threading

# 共享资源
counter = 0

# 创建锁
counter_lock = threading.Lock()

# 定义一个简单的线程类
class MyThread(threading.Thread):
    def run(self):
        global counter
        for _ in range(5):
            with counter_lock:  # 使用锁保护临界区
                counter += 1
                print(threading.current_thread().name, "Counter:", counter)

# 创建两个线程实例
thread1 = MyThread(name="Thread-1")
thread2 = MyThread(name="Thread-2")

# 启动线程
thread1.start()
thread2.start()

# 主线程等待所有子线程结束
thread1.join()
thread2.join()

print("Main thread exiting")

高级用法:

使用线程池

import concurrent.futures
import time

# 定义一个简单的任务函数
def task(name):
    print(f"{name} is running")
    time.sleep(2)
    return f"{name} is done"

# 使用线程池
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    # 提交任务给线程池
    future_to_name = {executor.submit(task, f"Thread-{i}"): f"Thread-{i}" for i in range(5)}

    # 获取任务结果
    for future in concurrent.futures.as_completed(future_to_name):
        name = future_to_name[future]
        try:
            result = future.result()
            print(f"{name}: {result}")
        except Exception as e:
            print(f"{name}: {e}")

使用Condition进行线程间通信

import threading
import time

# 共享资源
shared_resource = None

# 创建条件变量
condition = threading.Condition()

# 定义一个写线程
class WriterThread(threading.Thread):
    def run(self):
        global shared_resource
        for _ in range(5):
            with condition:
                shared_resource = "Write data"
                print("Writer wrote:", shared_resource)
                condition.notify()  # 通知等待的线程
                condition.wait()  # 等待其他线程通知

# 定义一个读线程
class ReaderThread(threading.Thread):
    def run(self):
        global shared_resource
        for _ in range(5):
            with condition:
                while shared_resource is None:
                    condition.wait()  # 等待写线程通知
                print("Reader read:", shared_resource)
                shared_resource = None
                condition.notify()  # 通知写线程

# 创建写线程和读线程
writer_thread = WriterThread()
reader_thread = ReaderThread()

# 启动线程
writer_thread.start()
reader_thread.start()

# 主线程等待所有子线程结束
writer_thread.join()
reader_thread.join()

print("Main thread exiting")

这些例子涵盖了一些基础和高级的多线程用法。请注意,在Python中由于全局解释器锁(GIL)的存在,多线程并不能充分利用多核处理器。如果需要充分利用多核处理器,可以考虑使用multiprocessing模块进行多进程编程。

原文地址:https://www.toutiao.com/article/7304442403006530087/

延伸 · 阅读

精彩推荐
  • PythonPython 抓取微信公众号账号信息的方法

    Python 抓取微信公众号账号信息的方法

    搜狗微信搜索提供两种类型的关键词搜索,一种是搜索公众号文章内容,另一种是直接搜索微信公众号。这篇文章主要介绍了Python 抓取微信公众号账号信息...

    IT白鸽9812021-07-12
  • Pythontensorflow更改变量的值实例

    tensorflow更改变量的值实例

    今天小编就为大家分享一篇tensorflow更改变量的值实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    勿在浮沙筑高台LS8842021-03-23
  • PythonPython爬虫基础之selenium库的用法总结

    Python爬虫基础之selenium库的用法总结

    今天带大家来学习selenium库的使用方法及相关知识总结,文中非常详细的介绍了selenium库,对正在学习python的小伙伴很有帮助,需要的朋友可以参考下...

    一腔诗意醉了酒7222021-11-12
  • PythonPython3读取UTF-8文件及统计文件行数的方法

    Python3读取UTF-8文件及统计文件行数的方法

    这篇文章主要介绍了Python3读取UTF-8文件及统计文件行数的方法,涉及Python读取指定编码文件的相关技巧,需要的朋友可以参考下 ...

    皮蛋5092020-07-05
  • Python详解Python中__str__和__repr__方法的区别

    详解Python中__str__和__repr__方法的区别

    这篇文章主要介绍了__str__和__repr__方法的区别 ,__str__和__repr__是基本的内置方法,使用时的区别也是Python学习当中的基础,需要的朋友可以参考下 ...

    脚本之家4322020-06-09
  • PythonPython新手们容易犯的几个错误总结

    Python新手们容易犯的几个错误总结

    python语言里面有一些小的坑,特别容易弄混弄错,初学者若不注意的话,很容易坑进去,下面我给大家深入解析一些这几个坑,希望对初学者有所帮助,需...

    菜鸟学Python5402020-09-27
  • PythonPython+matplotlib绘制条形图和直方图

    Python+matplotlib绘制条形图和直方图

    Matplotlib是Python的绘图库,它能让使用者很轻松地将数据图形化,并且提供多样化的输出格式。本文将为大家介绍如何用matplotlib绘制条形图和直方图,感兴...

    codingchen3362022-12-08
  • Python给Python入门者的一些编程建议

    给Python入门者的一些编程建议

    这篇文章主要介绍了给Python入门者的一些编程建议,包括对集合初始化和GIL理解等一些需要注意的地方,需要的朋友可以参考下...

    Python教程网2642020-07-15