python 多线程中同步的小例子

来源:互联网 发布:二手笔记本 知乎 编辑:程序博客网 时间:2024/06/05 10:59

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 在一个资源池中,获取资源# Author: zhang# Date: 2015-7-27import timeimport osimport 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()

例子中有一个共同的资源池,利用多线程获取其中的资源,但要保证数据的同步,即在某一次获取过程中,仅有一个线程可以对资源池进行操作。





0 0