线程,线程锁,线程队列-------之(线程锁)(线程队列)

线程锁

---1---线程锁:当有一个数据有多个线程都可以对其进行修改的时候,任何一个线程改变它都会对其他线程造成影响,

如果我们某一个线程在使用完之前,其他线程不能对其修改,就需要对这个线程增加一个线程锁

代码实现

count = 0
def get_money(money):
    global count
    count += money
    count += money
    count -= money
lock = threading.Lock()
def lock_thread(money):
    # acquire 捕获
#加锁
    lock.acquire()

    time.sleep(random.randint(1,3))
    print('当前线程为',threading.current_thread().name)
    get_money(money)
    time.sleep(random.randint(1,3))
    print('当前线程为', threading.current_thread().name)
#解锁
    lock.release()

#创建线程 的参数为一个 元组类型
# 主线程 开辟一个分线程
thread1 = threading.Thread(target=lock_thread,name='thread1',args=(1000,))
thread2 = threading.Thread(target=lock_thread,name='thread2',args=(2000,))
thread1.start()      
thread2.start()     
print('hello world')

# join注重的整体,线程1没有执行完,线程2不能执行
# lock注重的是局部 某一个变量没有用完 其他线程不能使用
thread1.join()
thread2.join()

执行结果:

---2---线程队列

代码实现:

import queue
#创建一个线程队列
# 队列:FIFO first in first out  先进先出
q = queue.Queue()
for i in range(5):
    # 将内容放置到线程队列中
    q.put(i)
while not q.empty():
    print(q.get())

print('------------------------------------------')

#LIFO last in first out 后进先出
p = queue.LifoQueue()
for i in range(5):
    p.put(i)
while not p.empty():
    print(p.get())

执行结果:

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值