#!/usr/bin/env python# -*- coding: utf-8 -*-import threadingimport Timeimport randomdef 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 (+): 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 () #信号量, number of threads allowed to run concurrently Def thread_demo_lock (): for i in range (: #sl =threading. Thread (Target=worker_func_lock,args=[glock]) sl=threading. Thread (Target=worker_func_lock,args=[gsem]) #参数传入信号量 sl.start () if __name__== "__main__": #sinple_thread_demo () #通过锁实现串行 Thread_demo_lock () #实现同时运行多个线程工作, mainly through the semaphore settings, but still executed on a CPU, the specific implementation of the example can be implemented in the function, to achieve single-core multi-concurrency
This article is from the "DBSpace" blog, so be sure to keep this source http://dbspace.blog.51cto.com/6873717/1882455
PYTHON Multi-threaded semaphore