python 多线程中同步的小例子

#!/usr/bin/python# -*- coding: UTF-8 -*-# 在一个资源池中,获取资源# Author: zhang# Date: 2015-7-27import timeimport osimport threading# 其他的一些可添加操作,,这里为休眠def doSomething():time.sleep(1)# 获取资源def getResource(threadid):global iglobal lockwhile True:lock.acquire() # 上锁if i != 0:i = i-1print('the current thread id is ',threadid)print('the current left resource is ',i)else:print('the left resource is none')os._exit(0)lock.release()doSomething()i = 20 # 资源数量lock = threading.Lock()# 创建多个线程for k in range(10):child_thread = threading.Thread(target=getResource,args=(k,))child_thread.start()例子中有一个共同的资源池,利用多线程获取其中的资源,但要保证数据的同步,即在某一次获取过程中,仅有一个线程可以对资源池进行操作。

版权声明:本文为博主原创文章,未经博主允许不得转载。

但我自信,我能点亮心烛,化解心灵的困惑。

python 多线程中同步的小例子

相关文章:

你感兴趣的文章:

标签云: