今天写了一下多线程脚本,准备跑个测试。结果屏幕输出的打印信息看的我直头晕。只好写个简单的,只有三个线程的脚本,看看发生了什么。
然后我就明白了,同时向一个终端,比如一个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文本文件,里面就是正常的了。