threading 对 _thread(py2为thread),进行了封装。
- 第一种:
把需要运行的函数传入到 Thread实例中 来执行, - 第二种
自己写一个thread class,直接从Thread继承,把线程执行的代码放到这个新的 class里。
import threading
import time
from queue import Queue
def thread_job():
print('### Thread {} is running ###'.format(threading.current_thread()))
def main():
added_thread = threading.Thread(target=thread_job)
print(threading.active_count())
print(threading.enumerate())
print(threading.current_thread())
added_thread.start()
print(threading.active_count())
# MainThread wait this thread, arguments is seconds.
added_thread.join()
print('all done')
# Queue
def job(li, q):
for i in range(len(li)):
li[i] = li[i]**2
q.put(li)
def multiThreading():
q = Queue()
threads = []
data = [[1,2,3],[4,5,6],[7,8,9]]
for i in range(3):
t = threading.Thread(target=job, args=(data[i], q))
t.start()
threads.append(t)
for thread in threads:
thread.join()
results = []
for _ in range(3):
results.append(q.get())
print(results)
# Lock
def job1():
global A
lock.acquire()
for i in range(6):
time.sleep(1)
A.append(0)
print('job1', A)
lock.release()
def job2():
global A
lock.acquire()
for i in range(5):
time.sleep(1)
A.append(1)
print('job2', A)
lock.release()
def mainLock():
t1 = threading.Thread(target=job1)
t2 = threading.Thread(target=job2)
t1.start()
t2.start()
t1.join()
t2.join()
if __name__ == '__main__':
# multiThreading()
# main()
lock = threading.Lock()
A = ['A']
mainLock()
# 没有lock
# job2 ['A', 1]
# job1 ['A', 1, 0]
# job1 ['A', 1, 0, 0]
# job2 ['A', 1, 0, 0, 1]
# job1 ['A', 1, 0, 0, 1, 0]
# job2 ['A', 1, 0, 0, 1, 0, 1]
# job1 ['A', 1, 0, 0, 1, 0, 1, 0]
# job2 ['A', 1, 0, 0, 1, 0, 1, 0, 1]
# job2 ['A', 1, 0, 0, 1, 0, 1, 0, 1, 1]
# job1 ['A', 1, 0, 0, 1, 0, 1, 0, 1, 1, 0]
# job1 ['A', 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0]
# lock
job1 ['A', 0]
job1 ['A', 0, 0]
job1 ['A', 0, 0, 0]
job1 ['A', 0, 0, 0, 0]
job1 ['A', 0, 0, 0, 0, 0]
job1 ['A', 0, 0, 0, 0, 0, 0]
job2 ['A', 0, 0, 0, 0, 0, 0, 1]
job2 ['A', 0, 0, 0, 0, 0, 0, 1, 1]
job2 ['A', 0, 0, 0, 0, 0, 0, 1, 1, 1]
job2 ['A', 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
job2 ['A', 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
[Finished in 11.1s]