淘先锋技术网

首页 1 2 3 4 5 6 7

#!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)