鱼C论坛

 找回密码
 立即注册
查看: 1371|回复: 1

[已解决]python线程锁怎么用?

[复制链接]
发表于 2020-9-22 15:12:43 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
线程同步的方式有很多,哪种比较常用?
最佳答案
2020-9-27 09:24:17
本帖最后由 suchocolate 于 2020-9-27 09:26 编辑

两种方式:全局变量和队列。(以下代码抄自明日科技《python从入门到项目实践》)
1.全局变量+互斥锁:
  1. from threading import Thread,Lock
  2. import time
  3. n=100 # 共100张票

  4. def task():
  5.     global n
  6.     mutex.acquire()             # 上锁
  7.     temp=n                      # 赋值给临时变量
  8.     time.sleep(0.1)             # 休眠0.1秒
  9.     n=temp-1                    # 数量减1
  10.     print('购买成功,剩余%d张电影票'%n)
  11.     mutex.release()             # 释放锁

  12. if __name__ == '__main__':
  13.     mutex=Lock()                # 实例化Lock类
  14.     t_l=[]                      # 初始化一个列表
  15.     for i in range(10):
  16.         t=Thread(target=task)   # 实例化线程类
  17.         t_l.append(t)           # 将线程实例存入列表中
  18.         t.start()               # 创建线程
  19.     for t in t_l:
  20.         t.join()                # 等待子线程结束
复制代码
2.队列:
  1. from queue import Queue
  2. import random,threading,time

  3. # 生产者类
  4. class Producer(threading.Thread):
  5.     def __init__(self, name,queue):
  6.         threading.Thread.__init__(self, name=name)
  7.         self.data=queue
  8.     def run(self):
  9.         for i in range(5):
  10.             print("生成者%s将产品%d加入队列!" % (self.getName(), i))
  11.             self.data.put(i)
  12.             time.sleep(random.random())
  13.         print("生成者%s完成!" % self.getName())

  14. # 消费者类
  15. class Consumer(threading.Thread):
  16.     def __init__(self,name,queue):
  17.         threading.Thread.__init__(self,name=name)
  18.         self.data=queue
  19.     def run(self):
  20.         for i in range(5):
  21.             val = self.data.get()
  22.             print("消费者%s将产品%d从队列中取出!" % (self.getName(),val))
  23.             time.sleep(random.random())
  24.         print("消费者%s完成!" % self.getName())

  25. if __name__ == '__main__':
  26.     print('-----主线程开始-----')
  27.     queue = Queue()        # 实例化队列
  28.     producer = Producer('Producer',queue)   # 实例化线程Producer,并传入队列作为参数
  29.     consumer = Consumer('Consumer',queue)   # 实例化线程Consumer,并传入队列作为参数
  30.     producer.start()    # 启动线程Producer
  31.     consumer.start()    # 启动线程Consumer
  32.     producer.join()     # 等待线程Producer结束
  33.     consumer.join()     # 等待线程Consumer结束
  34.     print('-----主线程结束-----')

复制代码



小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-9-27 09:24:17 | 显示全部楼层    本楼为最佳答案   
本帖最后由 suchocolate 于 2020-9-27 09:26 编辑

两种方式:全局变量和队列。(以下代码抄自明日科技《python从入门到项目实践》)
1.全局变量+互斥锁:
  1. from threading import Thread,Lock
  2. import time
  3. n=100 # 共100张票

  4. def task():
  5.     global n
  6.     mutex.acquire()             # 上锁
  7.     temp=n                      # 赋值给临时变量
  8.     time.sleep(0.1)             # 休眠0.1秒
  9.     n=temp-1                    # 数量减1
  10.     print('购买成功,剩余%d张电影票'%n)
  11.     mutex.release()             # 释放锁

  12. if __name__ == '__main__':
  13.     mutex=Lock()                # 实例化Lock类
  14.     t_l=[]                      # 初始化一个列表
  15.     for i in range(10):
  16.         t=Thread(target=task)   # 实例化线程类
  17.         t_l.append(t)           # 将线程实例存入列表中
  18.         t.start()               # 创建线程
  19.     for t in t_l:
  20.         t.join()                # 等待子线程结束
复制代码
2.队列:
  1. from queue import Queue
  2. import random,threading,time

  3. # 生产者类
  4. class Producer(threading.Thread):
  5.     def __init__(self, name,queue):
  6.         threading.Thread.__init__(self, name=name)
  7.         self.data=queue
  8.     def run(self):
  9.         for i in range(5):
  10.             print("生成者%s将产品%d加入队列!" % (self.getName(), i))
  11.             self.data.put(i)
  12.             time.sleep(random.random())
  13.         print("生成者%s完成!" % self.getName())

  14. # 消费者类
  15. class Consumer(threading.Thread):
  16.     def __init__(self,name,queue):
  17.         threading.Thread.__init__(self,name=name)
  18.         self.data=queue
  19.     def run(self):
  20.         for i in range(5):
  21.             val = self.data.get()
  22.             print("消费者%s将产品%d从队列中取出!" % (self.getName(),val))
  23.             time.sleep(random.random())
  24.         print("消费者%s完成!" % self.getName())

  25. if __name__ == '__main__':
  26.     print('-----主线程开始-----')
  27.     queue = Queue()        # 实例化队列
  28.     producer = Producer('Producer',queue)   # 实例化线程Producer,并传入队列作为参数
  29.     consumer = Consumer('Consumer',queue)   # 实例化线程Consumer,并传入队列作为参数
  30.     producer.start()    # 启动线程Producer
  31.     consumer.start()    # 启动线程Consumer
  32.     producer.join()     # 等待线程Producer结束
  33.     consumer.join()     # 等待线程Consumer结束
  34.     print('-----主线程结束-----')

复制代码



小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-27 17:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表