python多线程操作数据

1.threading.Lock()

'''
 如果多个线程对某一资源同时进行修改,可能会存在不可预知的情况。为了修改数据的正确性,需要把这个资源锁住,只允许线程依次排队进去获取这个资源。当线程A操作完后,释放锁,线程B才能进入。如下脚本是开启多个线程修改变量的值,但输出结果每次都不一样。
 '''
 import threading

money = 0
def Order(n):
    global money
    money = money + n
    money = money - n

class thread(threading.Thread):
    def __init__(self, threadname):
        threading.Thread.__init__(self, name='线程' + threadname)
        self.threadname = int(threadname)

    def run(self):
        for i in range(1000000):
            Order(self.threadname)

t1 = thread('1')
t2 = thread('5')
t1.start()
t2.start()
t1.join()
t2.join()
print(money)
 
'''接下来我们用 threading.Lock() 锁住这个变量,等操作完再释放这个锁。lock.acquire() 给资源加一把锁,对资源处理完成之后,lock.release() 再释放锁。以下脚本执行结果都是一样的,但速度会变慢,因为线程只能一个个的通过。'''
import threading

money = 0
def Order(n):
    global money
    money = money + n
    money = money - n

class thread(threading.Thread):
    def __init__(self, threadname):
        threading.Thread.__init__(self, name='线程' + threadname)
        self.threadname = int(threadname)

    def run(self):
        for i in range(1000000):
            lock.acquire()
            Order(self.threadname)
            lock.release()
#        print('%s:Now timestamp is %s'%(self.name,time.time()))

lock = threading.Lock()
t1 = thread('1')
t2 = thread('5')
t1.start()
t2.start()
t1.join()
t2.join()
print(money)


2.threading.Condition()

'''threading.Condition() 可以理解为更加高级的锁,比 Lock 和 Rlock 的用法更高级,能处理一些复杂的线程同步问题。threading.Condition() 创建一把资源锁(默认是Rlock),提供 acquire() 和 release() 方法,用法和 Rlock 一致。此外 Condition 还提供 wait()、Notify() 和 NotifyAll() 方法。

wait():线程挂起,直到收到一个 Notify() 通知或者超时(可选参数),wait() 必须在线程得到 Rlock 后才能使用。

Notify() :在线程挂起的时候,发送一个通知,让 wait() 等待线程继续运行,Notify() 也必须在线程得到 Rlock 后才能使用。 Notify(n=1),最多唤醒 n 个线程。

NotifyAll() :在线程挂起的时候,发送通知,让所有 wait() 阻塞的线程都继续运行。

举例说明下 Condition() 使用'''
import threading,time

def TestA():
    cond.acquire()
    print('李白:看见一个敌人,请求支援')
    cond.wait()
    print('李白:好的')
    cond.notify()
    cond.release()

def TestB():
    time.sleep(2)
    cond.acquire()
    print('亚瑟:等我...')
    cond.notify()
    cond.wait()
    print('亚瑟:我到了,发起冲锋...')

if __name__=='__main__':
    cond = threading.Condition()
    testA = threading.Thread(target=TestA)
    testB = threading.Thread(target=TestB)
    testA.start()
    testB.start()
    testA.join()
    testB.join()


'''输出
#李白:看见一个敌人,请求支援
#亚瑟:等我...
#李白:好的
#亚瑟:我到了,发起冲锋...'''
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值