- Python线程创建
在Python中,创建线程有两种方式:直接创建Thread对象和继承Thread类创建线程。
直接创建Thread对象:
import threading
def func():
print("Hello, World!")
if __name__ == "__main__":
t = threading.Thread(target=func)
t.start()
继承Thread类创建线程:
import threading
class MyThread(threading.Thread):
def __init__(self):
super().__init__()
def run(self):
print("Hello, World!")
if __name__ == "__main__":
t = MyThread()
t.start()
- Python锁的使用
在Python中,使用锁来控制线程的访问,防止出现数据竞争和死锁。
创建锁对象:
import threading
lock = threading.Lock()
Lock类提供了两个方法,acquire()和release(),分别用于获取和释放锁。
加锁:
lock.acquire()
# 访问共享变量
lock.release()
示例1:多线程访问共享变量
import threading
count = 0
lock = threading.Lock()
def increment():
global count
for i in range(0, 100000):
# 加锁
lock.acquire()
count += 1
# 释放锁
lock.release()
if __name__ == "__main__":
threads = []
for i in range(0, 5):
t = threading.Thread(target=increment)
threads.append(t)
t.start()
for t in threads:
t.join()
print("count:", count)
示例2:避免死锁
import threading
lock1 = threading.Lock()
lock2 = threading.Lock()
def func1():
lock1.acquire()
# do something
lock2.acquire()
# do something
lock2.release()
lock1.release()
def func2():
lock2.acquire()
# do something
lock1.acquire()
# do something
lock1.release()
lock2.release()
if __name__ == "__main__":
t1 = threading.Thread(target=func1)
t2 = threading.Thread(target=func2)
t1.start()
t2.start()
t1.join()
t2.join()
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)