python threading有一个有趣的现象,起多个线程时,CPU 占用只有160%不到200%,这是由于GIL全局解释锁的原因,参考python基础之多线程锁机制
import time, threading
n = 1
def loop(i):
global n
n = n + i
n = n - i
print 'n: ', n
def run_thread():
while True:
loop(1)
print 'thread %s is running...' % threading.current_thread().name
t = threading.Thread(target=run_thread, name='LoopThread')
t2 = threading.Thread(target=run_thread, name='LoopThread2')
t.start()
t2.start()
t.join()
t2.join()
print 'thread %s ended.' % threading.current_thread().name