python:线程,多线程锁,多线程递归锁

Posted CanSun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python:线程,多线程锁,多线程递归锁相关的知识,希望对你有一定的参考价值。

#!usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = "Samson"

import threading,time
def run(n):
print("task", n)
time.sleep(2)
print("current thread:",threading.current_thread())#当前线程

t_obj = []#存线程实例
start_time = time.time()
for i in range(50):
t = threading.Thread(target=run,args=("t%s" %i,))
#t.setDaemon(True)#把当前线程设置为守护线程,必须在t.start()之前设置,作用为主线程将不会等待该子线程结束
t.start()
t_obj.append(t)
print("total thread:",threading.active_count())#总线程数
for t in t_obj:
t.join()#等待线程执行完
print("%s" %(abs(start_time-time.time())))

多线程锁
#!usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = "Samson"

import threading,time
def run(n):
lock.acquire()#锁上
global num
num += 1
#time.sleep(1)#会变为单线程
lock.release()#解锁
lock = threading.Lock()#创建锁
num = 0
t_obj = []#存线程实例
for i in range(50):
t = threading.Thread(target=run,args=("t%s" %i,))
t.start()
t_obj.append(t)
for t in t_obj:
t.join()
print("%s" %num)
多线程递归锁
#!usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = "Samson"

import threading,time
def run():
lock.acquire()#锁上
res = run1()
res2 = run2()
lock.release()#解锁
def run1():
lock.acquire()#锁上
global num
num += 1
lock.release()#解锁
def run2():
lock.acquire()#锁上
global num
num += 1
lock.release()#解锁
lock = threading.RLock()#创建递归锁
num = 0
for i in range(10):
t = threading.Thread(target=run)
t.start()
print("Now:",threading.active_count())
while threading.active_count() != 1:
print(threading.active_count())
else:
print("%s" %num)














































































以上是关于python:线程,多线程锁,多线程递归锁的主要内容,如果未能解决你的问题,请参考以下文章

多线程——GIL信号量递归锁

Python 多线程

python并发编程之多线程2------------死锁与递归锁,信号量等

python 并发编程 多线程 死锁现象与递归锁

百万年薪python之路 -- 并发编程之 多线程 二

IOS面试题(多线程) --- 锁