python中“调用栈”与“线程”的不同
** “调用栈”与“线程”之间的不同**调用栈: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()
线程代码:
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()
线程运行结果:
worker Starting
Thread-1 Starting
my_service Starting
worker Exiting
Thread-1 Exiting
my_service Exiting
调用栈运行结果:
a() starts
b() starts
c() starts
c() returns
b() returns
d() starts
d() returns
a() returns理解线程的并行过程以及各线程的运行时间,是学会利用线程的基础;调用栈的运行过程,是python中函数调用的基本运行方式,方便更容易理解局部与全局作用域。
涨姿势了 :victory:厉害了 感谢分享 谢谢分享:victory: :victory:
页:
[1]