参考
创建线程示例
import threading
from threading import Thread
import time
def test(x):
print(f'this is {x}')
time.sleep(1)
def get_thread():
# 创建十个线程运算test函数
threads = [Thread(target=test, args=(x, )) for x in [5]*10]
# 启动线程
[t.start() for t in threads]
# 输出线程数量
print(len(threading.enumerate()))
if __name__ == '__main__':
get_thread()
# 通过继承类创建线程
import threading
from threading import Thread
import time
# 实现线程类继承自Thread
class MyThread(Thread):
def __init__(self, x):
super().__init__()
self.x = x
def run(self):
print(f'this is {self.x}')
time.sleep(2)
def get_thread():
# 创建十个线程运算test函数
threads = [MyThread(x) for x in [5]*10]
# 启动线程
[t.start() for t in threads]
# 输出线程数量
print(len(threading.enumerate()))
if __name__ == '__main__':
get_thread()
线程非安全示例
import threading
from threading import Thread
import time
# 线程非安全示例
number = 0
class MyThread1(Thread):
def run(self):
global number
# 此处对全局变量进行1000次加
for i in range(100000):
number += 1
class MyThread2(Thread):
def run(self):
global number
# 此处对全局变量进行1000次减
for i in range(100000):
number -= 1
if __name__ == '__main__':
# 创建线程
threads1 = MyThread1()
threads2 = MyThread2()
threads1.start()
threads2.start()
# 按照逻辑应该输出0,但多次运行后会出现非0,因为两个线程同时对全局变量进行修改造成的
print(number)
线程安全示例
import threading
from threading import Thread
import time
# 线程非安全示例
number = 0
# 创建线程锁
lock = threading.Lock()
class MyThread1(Thread):
def run(self):
global number, lock
# 此处对全局变量进行1000次加
for i in range(1000000):
# 锁住
locked = lock.acquire()
if locked: # 如果获取了锁就进行操作,操作完后释放锁
number += 1
lock.release()
class MyThread2(Thread):
def run(self):
global number, lock
# 此处对全局变量进行1000次减
for i in range(1000000):
# 锁住
locked = lock.acquire()
if locked: # 如果获取了锁就进行操作,操作完后释放锁
number -= 1
lock.release()
if __name__ == '__main__':
# 创建线程
threads1 = MyThread1()
threads2 = MyThread2()
threads1.start()
threads2.start()
threads1.join()# 等待线程结束再往下走
threads2.join()
# 按照逻辑应该输出0,但多次运行后会出现非0,因为两个线程同时对全局变量进行修改造成的
print(number)
死锁
- 使用多个锁时候会出现死锁,避免方法是不使用多个锁或设置死锁超时等待
import threading
from threading import Thread
number = 100
mutex1 = threading.Lock() # 创建锁对象
mutex2 = threading.Lock()
class MyThread1(Thread):
def run(self):
global number
for i in range(1000):
if mutex1.acquire(): # 拿到锁就执行下面
number += 1
if mutex2.acquire():
print('this is mutex2')
mutex2.release()
mutex1.release() # 释放锁
print(number)
class MyThread2(Thread):
def run(self):
global number
for i in range(1000):
if mutex2.acquire(): # 拿到锁就执行下面
number += 1
if mutex1.acquire():
print('this is mutex2')
mutex1.release()
mutex2.release() # 释放锁
print(number)
def get_thread1():
l_thread = (MyThread1(), MyThread2())
for t in l_thread:
t.start()
if __name__ == '__main__':
get_thread1()