1、threading模块 cpu占用分摊在两个核上

#! -*- coding:utf-8 -*-
#!/usr/bin/env python 
  
  
import threading 
from time import sleep, ctime 
  
loops = [ 4, 2 ] 
  
def loop(nloop, nsec): 
    while 1:
        pass
  
def main(): 
  print '---starting at:', ctime() 
  threads = [] 
  nloops = range(len(loops)) 
  
  for i in nloops: 
    t = threading.Thread(target=loop, 
    args=(i, loops[i])) 
    threads.append(t) 
  
  for i in nloops:      # start threads 
    threads[i].start() 
  
  for i in nloops:      # wait for all 
    threads[i].join()    # threads to finish 
  
  print '---all DONE at:', ctime() 
  
if __name__ == '__main__': 
  main() 

 2、thread模块 cpu占用主要集中在1个核上

#! -*- coding:utf-8 -*-
#!/usr/bin/env python 
  
  
import thread 
from time import sleep, ctime 
  
loops = [4, 2] 
  
def loop(nloop, nsec, lock): 
  while 1:
    pass
    
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() 

 

posted on 2016-06-21 17:41  妞溜溜  阅读(1709)  评论(0)    收藏  举报