8516830 发表于 2018-8-13 08:05:42

PYTHON 多线程信号量

实现同时运行多个线程工作,主要通过信号量的设置,但还是在一个CPU上执行,具体要实现的例子可以放在函数里执行,实现单核多并发,还等待什么......  
#!/usr/bin/env python
  
# -*- coding: utf-8 -*-
  
import threading
  
import time
  
import random
  
def work_func():
  
    print "worker thread is started at %s"% threading.current_thread()
  
    random.seed()
  
    time.sleep(random.random())
  
    print "worker thread is finished at %s"%threading.current_thread()
  
def sinple_thread_demo():
  
    for i in range(100):
  
      t=threading.Thread(target=work_func)
  
      t.start()
  
def worker_func_lock(lock):
  
    lock.acquire()
  
    work_func()
  
    lock.release()
  
gLock=threading.Lock()
  
gSem=threading._Semaphore(100)#信号量,允许同时运行的线程数
  
def thread_demo_lock():
  
    for i in range(100):
  
      #sl=threading.Thread(target=worker_func_lock,args=)
  
      sl=threading.Thread(target=worker_func_lock,args=)#参数传入信号量
  
      sl.start()
  
if __name__=="__main__":
  
    #sinple_thread_demo()#通过锁实现串行
  
    thread_demo_lock()
页: [1]
查看完整版本: PYTHON 多线程信号量