具备4年工作经验,是否已熟练掌握多线程间五种通信方式?

2026-05-29 13:124阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1793个文字,预计阅读时间需要8分钟。

具备4年工作经验,是否已熟练掌握多线程间五种通信方式?

问题:有两个线程,线程A向一个集合中反复添加字符串abc,一共添加十次,当添加到第五次的时候,希望B线程能够收到A线程的通知,然后执行相关的业务操作。

线程A:pythonimport threading

def thread_a(collection): for i in range(10): collection.append(abc) if i==4: threading.Event().set() threading.Event().wait()

collection=[]thread_a(collection)

线程B:pythondef thread_b(collection): event=threading.Event() while True: event.wait() event.clear() # 执行相关业务操作 print(收到通知,执行业务操作)

threading.Thread(target=thread_b, args=(collection,)).start()

问题

有两个线程,A 线程向一个集合里面依次添加元素“abc”字符串,一共添加十次,当添加到第五次的时候,希望 B 线程能够收到 A 线程的通知,然后 B 线程执行相关的业务操作。线程间通信的模型有两种:共享内存和消息传递,以下方式都是基本这两种模型来实现的。

一、使用 volatile 关键字

基于 volatile 关键字来实现线程间相互通信是使用共享内存的思想。

阅读全文

本文共计1793个文字,预计阅读时间需要8分钟。

具备4年工作经验,是否已熟练掌握多线程间五种通信方式?

问题:有两个线程,线程A向一个集合中反复添加字符串abc,一共添加十次,当添加到第五次的时候,希望B线程能够收到A线程的通知,然后执行相关的业务操作。

线程A:pythonimport threading

def thread_a(collection): for i in range(10): collection.append(abc) if i==4: threading.Event().set() threading.Event().wait()

collection=[]thread_a(collection)

线程B:pythondef thread_b(collection): event=threading.Event() while True: event.wait() event.clear() # 执行相关业务操作 print(收到通知,执行业务操作)

threading.Thread(target=thread_b, args=(collection,)).start()

问题

有两个线程,A 线程向一个集合里面依次添加元素“abc”字符串,一共添加十次,当添加到第五次的时候,希望 B 线程能够收到 A 线程的通知,然后 B 线程执行相关的业务操作。线程间通信的模型有两种:共享内存和消息传递,以下方式都是基本这两种模型来实现的。

一、使用 volatile 关键字

基于 volatile 关键字来实现线程间相互通信是使用共享内存的思想。

阅读全文