multithreading - 简单线程事件示例

标签 multithreading python-3.x

很难说出这里问的是什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或言辞激烈,无法以目前的形式合理回答。如需帮助澄清此问题以便可以重新打开,visit the help center .




8年前关闭。




我正在阅读 Python 3 的 Threading documentation但我无法理解 Material 。

我有两个计时器并排运行,但我不知道如何让这两个线程相互交互。锁定,传递事件或任何东西。

有人可以在这里转储一个简单的完整示例,并简要说明它的作用吗?

我正在尝试学习 3.3,所以如果可能的话,您是否能够发布适用于此版本的代码。我还发现我找到的教程并没有让我知道他们正在举例的 Python 版本。

最佳答案

基于 queue 的示例documentation :

#!python3
import threading
from queue import Queue
import time

# lock to serialize console output
lock = threading.Lock()

def do_work(item):
    time.sleep(.1) # pretend to do some lengthy work.
    # Make sure the whole print completes or threads can mix up output in one line.
    with lock:
        print(threading.current_thread().name,item)

# The worker thread pulls an item from the queue and processes it
def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

# Create the queue and thread pool.
q = Queue()
for i in range(4):
     t = threading.Thread(target=worker)
     t.daemon = True  # thread dies when main thread (only non-daemon thread) exits.
     t.start()

# stuff work items on the queue (in this case, just a number).
start = time.perf_counter()
for item in range(20):
    q.put(item)

q.join()       # block until all tasks are done

# "Work" took .1 seconds per task.
# 20 tasks serially would be 2 seconds.
# With 4 threads should be about .5 seconds (contrived because non-CPU intensive "work")
print('time:',time.perf_counter() - start)

输出:
Thread-3 2
Thread-1 0
Thread-2 1
Thread-4 3
Thread-3 4
Thread-1 5
Thread-2 6
Thread-4 7
Thread-3 8
Thread-1 9
Thread-2 10
Thread-4 11
Thread-3 12
Thread-1 13
Thread-2 14
Thread-4 15
Thread-1 17
Thread-3 16
Thread-2 18
Thread-4 19
time: 0.5017914706686906

关于multithreading - 简单线程事件示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16199793/

相关文章:

python - Python 中的 Null 字节表示

java - 线程安全的 HashMap ?

c# - Socket.*Async 方法是线程化的吗?

asp.net - 如果在 ASP.NET 完成其页面处理之前触发后台线程执行,会发生什么情况?

java - wait 在对象上调用,而 sleep 在线程上调用

python - 如何在python中对具有特殊日期结构的DataFrame进行排序?

multithreading - 内存防护是否会阻塞多核CPU中的线程?

Python - 元类装饰器 - 如何使用@classmethod

python - 匹配线性系统 ax+by=c 的正则表达式

python - 关于在 Python3 中将空格与一元运算符一起使用的逻辑