import threading
L = threading.Lock()
defhelloworld(what, ThreadName):
L.acquire() # 线程锁print'this is {}, and this is ThreadName: {}'.format(what, ThreadName)
L.release() # 释放锁# for 循环多次执行这个函数for i in range(20):
new_task(hellowrold, 3 ('what', 'thread-name-{}'.format(i))
# 这样每次就会执行一次函数,当函数释放锁之后才执行下一次,# L.acquire() 和 L.release() 是成对使用的
多线程处理高并发 – 线程池
import multiprocessing
defprint_time(s, threadNname, delay, **kwargs):if kwargs.get('lock', None) isnotNone:
print('get lock')
kwargs.get('lock').acquire()
count = 0while count < 5:
time.sleep(delay)
count += 1
print('this thread name is {threadname} and 当前时间是 {timename}'.format(timename=time.ctime(time.time()),
threadname=threadNname))
if kwargs.get('lock', None) isnotNone:
kwargs.get('lock').release()
pass
s = multiprocessing.Semaphore(2) #设置线程池的大小,每次只可以而同事启动2个线程for i in range(20):
"""
入口函数
"""
p = multiprocessing.Process(target=print_time, args=(s, 'xiancheng{}'.format(i), 3), kwargs={'lock':s})
p.start()