Python编程:threading多线程

简介: Python编程:threading多线程

直接调用

import threading
import time
def run(n):
    print("task:", n)
    time.sleep(2)
t1 = threading.Thread(target=run, args=("t1",))
t2 = threading.Thread(target=run, args=("t2",))
t3 = threading.Thread(target=run, args=("t3",))
t1.start()
t2.start()
t3.start()
"""
task: t1
task: t2
task: t3
"""

继承式调用

import threading
import time
class MyThread(threading.Thread):
    def __init__(self, n, sleep_time):
        super(MyThread, self).__init__()
        self.n = n
        self.sleep_time = sleep_time
    def run(self):  # 需要运行的代码
        print("task:", self.n)
        time.sleep(self.sleep_time)
        print("task done", self.n, threading.current_thread(), threading.active_count())
t1 = MyThread("t1", 2)
t2 = MyThread("t2", 3)
t3 = MyThread("t3", 4)
t1.start()
t2.start()
t3.start()
# 等待线程执行完毕继续主线程,阻塞
t1.join()  # wait()
t2.join()
t3.join()
print("...main...", threading.current_thread(), threading.active_count())  # 主线程
"""
task: t1
task: t2
task: t3
task done t1 <MyThread(Thread-1, started 7112)> 4
task done t2 <MyThread(Thread-2, started 5448)> 3
task done t3 <MyThread(Thread-3, started 4552)> 2
...main... <_MainThread(MainThread, started 2948)> 1
"""

多线程调用

# 主线程与子线程是并行的
import threading
import time
def run(n):
    print("task:", n)
    time.sleep(2)
    print("task done", n)
start_time = time.time()
threads = []  # 保存线程列表
for i in range(5):
    t = threading.Thread(target=run, args=("t%s"%i,))
    t.start()
    threads.append(t)
# 将所有线程阻塞
for t in threads:
    t.join()
end_time = time.time()
print("time:", end_time - start_time)
"""
task: t0
task: t1
task: t2
task: t3
task: t4
task done t4
task done t2
task done t3
task done t1
task done t0
time: 2.0103650093078613
"""

守护线程

import threading
import time
def run(n):
    print("task:", n)
    time.sleep(2)
    print("task done", n)
start_time = time.time()
threads = []  # 保存线程列表
for i in range(5):
    t = threading.Thread(target=run, args=("t%s"%i,))
    t.setDaemon(True)  # 设置为守护线程,主线程停止随之停止
    t.start()
    threads.append(t)
time.sleep(2)  # 等待部分线程执行完毕
end_time = time.time()
print("time:", end_time - start_time)
"""
task: t0
task: t1
task: t2
task: t3
task: t4
task done t2
task done t4
task done t3
task done t1
task done t0
time: 2.0087130069732666
"""

互斥锁

import threading
import time
num = 0
lock = threading.Lock()  # 实例化互斥锁
def run(n):
    global num
    lock.acquire()  # 申请锁
    time.sleep(2)
    num += 1
    lock.release()  # 释放锁
    print(num)
start_time = time.time()
threads = []  # 保存线程列表
for i in range(5):
    t = threading.Thread(target=run, args=("t%s"%i,))
    t.start()
    threads.append(t)
for thread in threads:
    thread.join()  # 等待部分线程执行完毕
end_time = time.time()
print("time:", end_time - start_time)
print("num:", num)
"""
1
2
3
4
5
time: 10.027688980102539
num: 5
"""

递归锁

import threading
import time
num = 0
lock = threading.RLock()  # 实例化递归锁,此处用普通互斥锁会卡死
def run1():
    print("run1_start")
    lock.acquire() # 第二级锁
    print("run1")
    lock.release()
def run2():
    lock.acquire()  # 第二级锁
    print("run2")
    lock.release()
def run():
    lock.acquire()  # 第一级锁
    print("run1_begin")
    run1()
    print("run2_begin")
    run2()
    print("run_end")
    lock.release()  # 释放锁
start_time = time.time()
t = threading.Thread(target=run)
t.start()
# t.join()  # 等待全部线程执行完毕
while threading.active_count() > 1:
    print(threading.current_thread())
end_time = time.time()
print("time:", end_time - start_time)
"""
run1_begin
<_MainThread(MainThread, started 22552)>
<_MainThread(MainThread, started 22552)>
<_MainThread(MainThread, started 22552)>
run1_start
<_MainThread(MainThread, started 22552)>
run1
run2_begin
run2
run_end
time: 0.0
"""

信号锁

import threading
import time
semaphore = threading.BoundedSemaphore(5)  # 设置信号量,最多允许5个线程同时运行
def run(n):
    semaphore.acquire()  # 信号锁
    time.sleep(1)
    print("run", n)
    semaphore.release()
start_time = time.time()
for i in range(10):
    t = threading.Thread(target=run, args=(i,))
    t.start()
# 等待全部线程执行完毕
while threading.active_count() != 1:
    pass
end_time = time.time()
print("time:", end_time - start_time)
"""
run 1
run 2
run 4
run 0
run 3
run 5
run 7
run 8
run 9
run 6
time: 2.061771869659424
"""
相关文章
|
1天前
|
Python
Python编程案例:同一工作簿不同表单特定数据添加到工作簿的另一表单里
Python编程案例:同一工作簿不同表单特定数据添加到工作簿的另一表单里
|
1天前
|
iOS开发 MacOS Python
Python编程案例:根据姓名归档论文、报告
Python编程案例:根据姓名归档论文、报告
|
1天前
|
IDE 开发工具 数据安全/隐私保护
Python编程实现批量md5加密pdf文件
Python编程实现批量md5加密pdf文件
|
1天前
|
安全 网络安全 数据安全/隐私保护
Python渗透测试之流量分析:流量嗅探工具编程
Python渗透测试之流量分析:流量嗅探工具编程
10 0
|
1天前
|
IDE 搜索推荐 网络安全
Python编程:编写被动信息搜集之网址的IP及Whois查询
Python编程:编写被动信息搜集之网址的IP及Whois查询
|
1天前
|
IDE 开发工具 iOS开发
Python编程案例:招生档案按省份地区归档
Python编程案例:招生档案按省份地区归档
|
1天前
|
IDE 开发工具 iOS开发
Python编程案例:中文金额转换并计算
Python编程案例:中文金额转换并计算
|
3月前
|
安全 Python
告别低效编程!Python线程与进程并发技术详解,让你的代码飞起来!
【7月更文挑战第9天】Python并发编程提升效率:**理解并发与并行,线程借助`threading`模块处理IO密集型任务,受限于GIL;进程用`multiprocessing`实现并行,绕过GIL限制。示例展示线程和进程创建及同步。选择合适模型,注意线程安全,利用多核,优化性能,实现高效并发编程。
60 3
|
3月前
|
安全 数据安全/隐私保护 数据中心
Python并发编程大挑战:线程安全VS进程隔离,你的选择影响深远!
【7月更文挑战第9天】Python并发:线程共享内存,高效但需处理线程安全(GIL限制并发),适合IO密集型;进程独立内存,安全但通信复杂,适合CPU密集型。使用`threading.Lock`保证线程安全,`multiprocessing.Queue`实现进程间通信。选择取决于任务性质和性能需求。
81 1
|
3月前
|
Python
解锁Python并发新世界:线程与进程的并行艺术,让你的应用性能翻倍!
【7月更文挑战第9天】并发编程**是同时执行多个任务的技术,提升程序效率。Python的**threading**模块支持多线程,适合IO密集型任务,但受GIL限制。**multiprocessing**模块允许多进程并行,绕过GIL,适用于CPU密集型任务。例如,计算平方和,多线程版本使用`threading`分割工作并同步结果;多进程版本利用`multiprocessing.Pool`分块计算再合并。正确选择能优化应用性能。
29 1