threading
# import time
# import threading
# begin = time.time()
#
# def foo(n):
# print('foo%s'%n)
# time.sleep(1)
# print('end foo')
#
# def bar (n):
# print('bar%s'%n)
# time.sleep(3)
# print('end bar')
#
# t1 = threading.Thread(target=foo,args=(1,))
#
# t2 = threading.Thread(target=bar,args=(2,))
#
# t1.start()
# t2.start()
#
# print('************')
# t1.join()
# t2.join()
#
# end = time.time()
# print(end - begin)
#在python里:
# 没有多线程
# if任务是io密集型的,可以用多线程
# 是计算密集型的,sorry,改C。
import time
import threading
from time import ctime,sleep
def music(func):
for i in range(2):
print('begin listening to %s.%s'%(func,ctime()))
sleep(1)
print('end listening %s' %ctime())
def move(func):
for i in range(2):
print('begin listening to %s.%s'%(func,ctime()))
sleep(5)
print('end listening %s' %ctime())
threads = []
t1 = threading.Thread(target=music,args=('喜欢你',))
threads.append(t1)
t2 = threading.Thread(target=move,args=('杀手之王',))
threads.append(t2)
if __name__ == '__main__':
#开启t2的守护进程
t2.setDaemon(True)
for i in threads:
i.start()
#IO堵塞
i.join()
print('end...............%s' %ctime())
输出结果:
begin listening to 喜欢你.Thu Jan 23 10:50:11 2020
begin listening to 杀手之王.Thu Jan 23 10:50:11 2020end...............Thu Jan 23 10:50:11 2020
end listening Thu Jan 23 10:50:12 2020
begin listening to 喜欢你.Thu Jan 23 10:50:12 2020
end listening Thu Jan 23 10:50:13 2020
end listening Thu Jan 23 10:50:16 2020
begin listening to 杀手之王.Thu Jan 23 10:50:16 2020
end listening Thu Jan 23 10:50:21 2020
#类方法启用并发
'''
import threading
import time
class foo (threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num = num
def run(self):
print('running on num:%s' %self.num)
time.sleep(3)
if __name__ == '__main__':
t1 = foo(1)
t2 = foo(2)
t1.start()
t2.start()
'''
同步锁
import threading
import time
num = 100
r = threading.Lock() #同步锁
def addNum():
global num #在每个线程都获取这个全局变量
r.acquire() #启用同步锁
num -= 1
r.release() #释放同步锁
thread_list = []
for i in range(100):
t = threading.Thread(target=addNum)
t.start()
thread_list.append(t)
for i in thread_list:
t.join()
print('final num:',num)
信号量
import threading,time
class myThread(threading.Thread):
def run(self):
if semaphore.acquire():
print(self.name)
time.sleep(3)
semaphore.release()
if __name__=="__main__":
semaphore = threading.BoundedSemaphore(5) #看似同时出现5个线程
thr = []
for i in range(33):
thr.append(myThread())
for t in thr:
t.start()