请教一个 Python 中线程共享数据的问题 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
smdbh
V2EX    Python

请教一个 Python 中线程共享数据的问题

  •  
  •   smdbh 2024-10-08 10:56:44 +08:00 1792 次点击
    这是一个创建于 367 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我想在 main 和它建立的线程间共享数据,在线程中执行逻辑,更新数据,主线程中读取判断。

    1. 由于数据较多,使用 dataclass 当 struct 用
    2. 线程中写,main 中只读,所有没有加锁 实际使用发现,这个数据共享不是完全引用,变量地址(使用 id 查看两边地址)会有改变,导致 main 和 thread 中的变量不是一个东西了,监测失败。
    3. tricky 的是,第一次创建的线程没有问题。跑完一次,第二次再来一次就大概率出问题,后续再尝试就一直会出问题了,偶尔会成功。 请问如果要实现多线程共享数据的读写,有什么最佳实现和模板吗
    7 条回复    2024-11-13 18:32:53 +08:00
    smdbh
        1
    smdbh  
    OP
       2024-10-08 11:32:02 +08:00
    补充下,我当前是将 dataclass 的结构当参数传入 threading.Thead 的参数中,这个操作是否有问题
    djangovcps
        2
    djangovcps  
       2024-10-08 11:40:16 +08:00
    threading.lock ?
    F532uKfxnXPiFdnC
        3
    F532uKfxnXPiFdnC  
       2024-10-08 12:01:58 +08:00
    ```python
    import threading
    import time
    from concurrent.futures import ThreadPoolExecutor
    import unittest
    from dataclasses import dataclass, field
    from threading import Lock
    import multiprocessing

    @dataclass
    class SharedData:
    value: int = 0
    # Using a Lock to ensure thread-safety when accessing shared data
    lock: Lock = field(default_factory=Lock, init=False, repr=False)

    def increment(self):
    with self.lock:
    self.value += 1

    def get_value(self):
    with self.lock:
    return self.value

    def worker(data: SharedData, num_iterations: int):
    local_sum = 0
    for _ in range(num_iterations):
    local_sum += 1
    # Use a lock to safely update the shared data
    with data.lock:
    data.value += local_sum

    class TestSharedDataThreadSafety(unittest.TestCase):
    def test_concurrent_increments(self):
    shared_data = SharedData()
    # Use 2x CPU count for threads to test both CPU-bound and I/O-bound scenarios
    num_threads = multiprocessing.cpu_count() * 2
    num_iteratiOns= 1000000 // num_threads

    with ThreadPoolExecutor(max_workers=num_threads) as executor:
    futures = [executor.submit(worker, shared_data, num_iterations) for _ in range(num_threads)]
    for future in futures:
    future.result()

    expected_value = num_threads * num_iterations
    self.assertEqual(shared_data.get_value(), expected_value,
    f"Expected {expected_value}, but got {shared_data.get_value()}")

    def test_race_condition(self):
    shared_data = SharedData()
    race_detected = threading.Event()

    def racer():
    with shared_data.lock:
    initial_value = shared_data.value
    time.sleep(0.001) # Simulate some work
    # Check if the value has changed, which would indicate a race condition
    if initial_value == shared_data.value:
    shared_data.value += 1
    else:
    race_detected.set()

    threads = [threading.Thread(target=racer) for _ in range(100)]
    for t in threads:
    t.start()
    for t in threads:
    t.join()

    self.assertFalse(race_detected.is_set(), "Race condition detected")

    def test_stress_test(self):
    shared_data = SharedData()
    stop_flag = threading.Event()

    def stress_worker():
    local_sum = 0
    while not stop_flag.is_set():
    local_sum += 1
    # Use a lock to safely update the shared data after intensive local computation
    with shared_data.lock:
    shared_data.value += local_sum

    # Use CPU count for threads to maximize resource utilization
    threads = [threading.Thread(target=stress_worker) for _ in range(multiprocessing.cpu_count())]
    for t in threads:
    t.start()

    time.sleep(5) # Run for 5 seconds to simulate prolonged stress
    stop_flag.set()

    for t in threads:
    t.join()

    print(f"Stress test final value: {shared_data.get_value()}")

    if __name__ == '__main__':
    unittest.main()
    ```
    ClericPy
        4
    ClericPy  
       2024-10-08 23:17:03 +08:00
    show me your code?
    milkpuff
        5
    milkpuff  
       2024-10-09 13:25:40 +08:00
    修改 data.a, data 的 id 不会变。
    UN2758
        6
    UN2758  
       331 天前
    @qianchengv 佬,你这大段的代码还不如贴一个 gist 链接呢,比这个方便阅读多了
    UN2758
        7
    UN2758  
       331 天前
    多线程,要么加锁,要么用 queue 之类的库,至于你的问题二,地址会移动可能是因为对象大小改变导致的重新分配地址
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     2968 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 30ms UTC 13:34 PVG 21:34 LAX 06:34 JFK 09:34
    Do have faith in what you're doing.
    ubao snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86