程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Use of Python multithreading

編輯:Python

1. Execution between threads is out of order ,cpu Execute the thread that is scheduled ;
2. The main thread waits for all child threads to finish before ending , Setting the daemon thread can realize that when the main thread ends, the child thread ends immediately ;
3. Setting up the guardian thread :1.threading.Thread(daemon=True),2. Thread object .setDaemon(True);
4. Sharing global variables between threads , There is a problem of resource competition .

'''
Execution between threads is out of order ,cpu Execute the thread that is scheduled
The main thread will wait for all child threads to finish before ending , Setting the daemon thread can realize that when the main thread ends, the child thread ends immediately
Setting up the guardian thread :1.threading.Thread(daemon=True),2. Thread object .setDaemon(True)
Sharing global variables between threads , There is a problem of resource competition
'''
# The import module ( Module name .py, Package name init.py)
import threading
import time
def task1(count):
# Get the current thread object
# t=threading.current_thread()
# print('Task1_name:',t.name)
print()
for i in range(count):
print('Task A ',i+1)
time.sleep(0.5)
def task2(content,count):
print('Task2_name:', threading.current_thread().name)
for i in range(count):
print(f'{content}__Task B ',i+1)
time.sleep(0.5)
if __name__ == '__main__':
t1=threading.Thread(target=task1,name='T1',daemon=True,args=(5,))
t2=threading.Thread(target=task2,name='T2',kwargs={'content':'Yes','count':5})
# Set the second way to guard the main thread
# t1.setDaemon(True)
t2.setDaemon(True)
t1.start()
t1.join() # Blocking function ,t1 Execute downward only after execution
t2.start()
# t2.join()
print('Main thread over')


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved