多线程时的屏幕打印信息

    今天写了一下多线程脚本,准备跑个测试。结果屏幕输出的打印信息看的我直头晕。只好写个简单的,只有三个线程的脚本,看看发生了什么。

    然后我就明白了,同时向一个终端,比如一个IDLE里面输出打印信息,也是利用CPU的时间片。虽然由于GIL的存在,python只能利用一个核,但是,依然会按照时间分片进行指令的操作。

   把信息输出到文本文件里,看起来就正常了。

代码如下:

import threading,time

class MyThread(threading.Thread):

    def __init__(self,threadname):
        threading.Thread.__init__(self, name=threadname)        

    def run(self):
        f_name = str(self.getName()) + '.txt' 
        f = file(f_name, 'a')        
        for i in range(1,11):
            print self.getName() ," ", i
            time.sleep(1)
            msg = str(self.getName())+ " "+str(i)+ '\n'
            f.write(msg)
        f.close()


if __name__ == '__main__':
    for i in range(1,4):
        t_name = 'thread' + str(i)
        obj = MyThread(t_name)
        obj.start()
        time.sleep(1)
        print obj

如果只看IDLE,那么打印信息是乱成这样的:

thread1   1
<MyThread(thread1, started)>thread1
  thread2    2
1
<MyThread(thread2, started)>
thread3   1
thread1thread2      32

<MyThread(thread3, started)>thread3
  thread1
>>>   thread2   2 
4
3
thread3thread1      35

thread2   4
thread3thread1      46

thread2   5
thread3thread1      57

thread2   6
thread1thread3      86

thread2   7
thread1   9
 thread2thread3      87

thread1thread2      109thread3

   8
thread2   10
thread3   9
thread3   10

如果再看生成的thread1.txt,  thread2.txt , thread3.txt文本文件,里面就是正常的了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值