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

The difference between call stack and thread in Python

編輯:Python

** “ The call stack ” And “ Threads ” Differences between **

The call stack :
def a():
print('a() starts')
b()
d()
print('a() returns')

def b():
print('b() starts')
c()
print('b() returns')

def c():
print('c() starts')
print('c() returns')

def d():
print('d() starts')
print('d() returns')

a()
Thread code :
import threading
import time

def worker():
print(threading.current_thread().getName(), 'Starting')
time.sleep(0.2)
print(threading.current_thread().getName(), 'Exiting')

def my_service():
print(threading.current_thread().getName(), 'Starting')
time.sleep(0.3)
print(threading.current_thread().getName(), 'Exiting')

t = threading.Thread(name='my_service', target=my_service)
w = threading.Thread(name='worker', target=worker)
w2 = threading.Thread(target=worker) # use default name

w.start()
w2.start()
t.start()

Thread running results :

worker Starting
Thread-1 Starting
my_service Starting
worker Exiting
Thread-1 Exiting
my_service Exiting

Call stack run result :
a() starts
b() starts
c() starts
c() returns
b() returns
d() starts
d() returns
a() returns

Understand the parallel process of threads and the running time of each thread , It is the foundation of learning to use threads ; Call the running process of the stack , yes python Basic operation mode of function call in , It is easier to understand local and global scopes .


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