ps:对cpu架构实现原理理解不深。暂时可以通过代码测试不同方法的性能。后续分析
有待学习:cpu、多核、io(多线程、多进程,多核cpu利用率)等的架构
python多线程和多进程编程(进程间通信)
1、加线程锁只有一个cpu占用率高90%+
#!/usr/bin/env python import thread from time import sleep, ctime loops = [100, 100] def loop(nloop, nsec, lock):
while 1:
pass
lock.release()
def main(): print '---starting threads...' locks = [] nloops = range(len(loops)) for i in nloops: lock = thread.allocate_lock() lock.acquire() locks.append(lock) for i in nloops: thread.start_new_thread(loop, (i, loops[i], locks[i])) for i in nloops: while locks[i].locked(): pass print '---all DONE at:', ctime() if __name__ == '__main__': main()
2、不加线程锁 开启一个进程,一个cpu占用率相当 20% 用到sshd服务
#!/usr/bin/env python import thread from time import sleep, ctime def loop0(): while 1: print '+++start loop 0 at:', ctime() def loop1(): while 1: print '***start loop 1 at:', ctime() def main(): print '------starting at:', ctime() thread.start_new_thread(loop0, ()) thread.start_new_thread(loop1, ()) sleep(200) print '------all DONE at:', ctime() if __name__ == '__main__': main()
浙公网安备 33010602011771号