#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 在一个资源池中。获取资源
# Author: zhang
# Date: 2015-7-27
import time
import os
import threading
# 其它的一些可加入操作,这里为休眠
def doSomething():
time.sleep(1)
# 获取资源
def getResource(threadid):
global i
global lock
while True:
lock.acquire() # 上锁
if i != 0:
i = i-1
print('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()
样例中有一个共同的资源池,利用多线程获取当中的资源。但要保证数据的同步,即在某一次获取过程中,仅有一个线程能够对资源池进行操作。
浙公网安备 33010602011771号