本文主要是介绍python-threading,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 创建线程示例
- 线程非安全示例
- 线程安全示例
- 死锁
参考
创建线程示例
import threading
from threading import Thread
import timedef 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 = xdef 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 += 1class MyThread2(Thread):def run(self):global number# 此处对全局变量进行1000次减for i in range(100000):number -= 1if __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 += 1lock.release()class MyThread2(Thread):def run(self):global number, lock# 此处对全局变量进行1000次减for i in range(1000000):# 锁住locked = lock.acquire()if locked: # 如果获取了锁就进行操作,操作完后释放锁number -= 1lock.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 Threadnumber = 100
mutex1 = threading.Lock() # 创建锁对象
mutex2 = threading.Lock()class MyThread1(Thread):def run(self):global numberfor i in range(1000):if mutex1.acquire(): # 拿到锁就执行下面number += 1if mutex2.acquire():print('this is mutex2')mutex2.release()mutex1.release() # 释放锁print(number)
class MyThread2(Thread):def run(self):global numberfor i in range(1000):if mutex2.acquire(): # 拿到锁就执行下面number += 1if 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()
这篇关于python-threading的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!