1、多线程(无锁):threading.Thread(target = ***).start()
1 import threading
2 import time
3 import random
4
5 def worker_func():
6 print('worker thread is started at %s' % threading.current_thread())
7 random.seed()
8 time.sleep(random.random())
9 print('worker thread is finished at %s' % threading.current_thread())
10
11 def simple_thread_demo():
12 for i in range(10):
13 threading.Thread(target=worker_func).start()
14
15 if __name__ == '__main__':
16 simple_thread_demo()
2、多线程(锁 & 单线程):<1> threading.Lock() <2> threading.Thread(target = ***,args = [***]).start()
1 #coding=utf-8
2 import threading
3 import random
4 import time
5
6 def worker_func():
7 print('worker thread is started at %s' % threading.current_thread())
8 random.seed()
9 time.sleep(random.random())
10 print('worker thread is finished at %s' % threading.current_thread())
11
12 def worker_func_lock(mylock):
13 mylock.acquire()
14 worker_func()
15 mylock.release()
16
17 gLock = threading.Lock() #创建线程锁
18
19 def thread_lock_demo():
20 for i in range(10):
21 threading.Thread(target=worker_func_lock,args=[gLock]).start() #开启线程
22
23 if __name__ == '__main__':
24 thread_lock_demo()
3、多线程(信号量 & 多线程):<1> threading.Semaphore() <2> threading.Thread(target = ***,args = [***]).start()
1 #coding=utf-8
2 import threading
3 import random
4 import time
5
6 def worker_func():
7 print('worker thread is started at %s' % threading.current_thread())
8 random.seed()
9 time.sleep(random.random())
10 print('worker thread is finished at %s' % threading.current_thread())
11
12 def worker_func_lock(mylock):
13 mylock.acquire()
14 worker_func()
15 mylock.release()
16
17 gSem = threading.Semaphore(3) #信号量为3
18
19 def thread_lock_demo():
20 for i in range(10):
21 threading.Thread(target=worker_func_lock,args=[gSem]).start() #开启线程
22
23 if __name__ == '__main__':
24 thread_lock_demo()