import time
import threading
# python中存在的GIL(全局解释器锁)问题:在同一时刻只能有一个线程进入解释器
# I/O密集型任务或函数
start = time.time()
def foo(n):
print('foo%s'%n)
time.sleep(1)
print('end foo')
def bar(n):
print('bar%s'%n)
time.sleep(2)
print('end bar')
t1 = threading.Thread(target=foo,args=(1,))
t2 = threading.Thread(target=bar,args=(2,))
t1.start()
t2.start()
print('....in the main....')
t1.join()
t2.join() # t1.join()表示如果t1没有执行完就不往下执行了
end = time.time()
print(end - start)
out:
foo1
bar2....in the main....
end foo
end bar
2.027029514312744
import time
import threading
# 计算密集型任务或函数
start = time.time()
def add(n):
sum = 0
for i in range(n):
sum += i
print(sum)
add(10000)
add(20000)
t1 = threading.Thread(target=add,args=(10000,))
t2 = threading.Thread(target=add,args=(20000,))
t1.start()
t2.start()
t1.join()
t2.join() # t1.join()表示如果t1没有执行完就不往下执行了
end = time.time()
print(end - start)
out:
49995000
199990000
49995000
199990000
0.032996177673339844
测试:
import threading
from time import ctime, sleep
# def music(func):
# for i in range(2):
# print('I was listening to %s. %s'%(func,ctime()))
# sleep(1)
#
# def move(func):
# for i in range(2):
# print('I was at the %s! %s'%(func,ctime()))
# sleep(5)
#
# if __name__ == '__main__':
# music('七里香')
# move('世界末路')
def music(func):
print(threading.current_thread())
for i in range(2):
print('I was listening to %s. %s' % (func, ctime()))
sleep(1)
print('end listening %s'%ctime())
def move(func):
print(threading.current_thread())
for i in range(2):
print('I was watching the %s! %s' % (func, ctime()))
sleep(5)
print('end watching %s'%ctime())
threads = []
t1 = threading.Thread(target=music,args=('七里香',))
threads.append(t1)
t2 = threading.Thread(target=move,args=('世界末路',))
threads.append(t2)
if __name__ == '__main__':
t1.setDaemon(True)
for t in threads:
# t.setDaemon(True) # 守护线程(其他线程一旦结束,守护线程也会立马结束)
t.start()
t.join()
print(threading.current_thread())
print('all over %s'%ctime())
out:
<Thread(Thread-10, started daemon 2796)>
<Thread(Thread-11, started 11004)>I was listening to 七里香. Sat Apr 25 21:40:59 2020
I was watching the 世界末路! Sat Apr 25 21:40:59 2020
end listening Sat Apr 25 21:41:00 2020
I was listening to 七里香. Sat Apr 25 21:41:00 2020
end listening Sat Apr 25 21:41:01 2020
end watching Sat Apr 25 21:41:04 2020
I was watching the 世界末路! Sat Apr 25 21:41:04 2020
end watching Sat Apr 25 21:41:09 2020
<_MainThread(MainThread, started 10796)>
all over Sat Apr 25 21:41:09 2020