码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-01-30 00:11:24      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:创建   post   star   body   art   pre   auth   count   主线程   

#!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:线程,多线程锁,多线程递归锁

标签:创建   post   star   body   art   pre   auth   count   主线程   

原文地址:https://www.cnblogs.com/cansun/p/8379709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!