Python中如何处理线程问题?

想问一个问题,既然 threading 模块里面 join 的官方解释是: join([timeout]) Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

那它是怎样去对 threading 是否 termaine 进行判断吗?还是 python 通过信号量来进行判断的,求大神解释


Python中如何处理线程问题?

3 回复

在Python里处理线程,标准库用threading,I/O密集型任务效果不错。CPU密集型的活建议用multiprocessing绕过GIL限制。

基础操作:

import threading
import time

def worker(num):
    print(f'线程 {num} 开始')
    time.sleep(2)
    print(f'线程 {num} 结束')

threads = []
for i in range(3):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

for t in threads:
    t.join()
print('所有线程完成')

共享数据用锁:

import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        with lock:
            counter += 1

threads = []
for _ in range(2):
    t = threading.Thread(target=increment)
    threads.append(t)
    t.start()

for t in threads:
    t.join()
print(f'最终计数: {counter}')  # 应该是200000

线程池(Python 3.2+):

from concurrent.futures import ThreadPoolExecutor
import time

def task(name):
    time.sleep(1)
    return f'{name}完成'

with ThreadPoolExecutor(max_workers=3) as executor:
    futures = [executor.submit(task, f'任务{i}') for i in range(5)]
    for future in futures:
        print(future.result())

队列通信:

import threading
import queue
import time

def producer(q):
    for i in range(5):
        time.sleep(0.5)
        q.put(i)
        print(f'生产: {i}')

def consumer(q):
    while True:
        item = q.get()
        if item is None:
            break
        print(f'消费: {item}')
        q.task_done()

q = queue.Queue()
prod = threading.Thread(target=producer, args=(q,))
cons = threading.Thread(target=consumer, args=(q,))

prod.start()
cons.start()
prod.join()
q.put(None)
cons.join()

简单说就是:I/O用线程,CPU用进程,共享数据要加锁。


你想要知道的答案全部在 threading.py 里面

最后这段中文我严重没看懂。请复述一下

回到顶部