Discuss / Python / 为什么print结果不一样

为什么print结果不一样

Topic source

我在process_student()里的print里加了\n才有换行,可是上面代码里没有\n,结果应该是连在一起的

import threading

local_school = threading.local()

def process_student():
    std = local_school.student
    print('Hello,%s (in %s)\n' % (std,threading.current_thread().name))

def process_thread(name):
    local_school.student = name

    process_student()

t1 = threading.Thread(target=process_thread,args=('Alice',),name='Thread-A')
t2 = threading.Thread(target=process_thread,args=('Bob',),name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()

写下自己的感想加深印象:之前写一个函数都是直接运行,不管他在哪里跑的。这一讲就是深入到计算机原理层面,所有的函数代码最终都是分配给进程里的线程,就像把汽车(函数)放到马路(进程)上的车道(线程)里,这就是创建Thread实例的过程,start()就是让车跑起来,join()等这辆车到了再运行后面的代码

因该是并行执行,先打印Thread_A,还没有打印换行就执行Tread_B,打印后最后是两个换行。因该可以看到结果有个空行。


  • 1

Reply