2301_77602568 2024-03-28 09:58 采纳率: 16.7%
浏览 5

python多线程数据冲突

python多线程数据冲突,每个线程访问同一个列表元素。
三个定义的全局变量必须要没办法转为局部变量。

def process_item(month):
    global json_data_object,pKmSFk8

    lock =threading.Lock()
    filed = request_data()
    with lock:
        json_data_object = {
            "city": "杭州",
            "month": month
        }

        pKmSFk8 = {
            "appId": "3c9208efcfb2f5b843eec8d96de6d48a",
            "method": "GETDAYDATA",
            "timestamp": filed.timestamp(),
            "clienttype": "WEB",
            "object": json_data_object,
            "secret": filed.secret()
        }
        time.sleep(1)
        #print(json_data_object)
        main_sql()


def main():
    # 这是一个你想要迭代的列表
    new = selecter()
    items = new.month_list()

    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:

        executor.map(process_item, items)

  • 写回答

2条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2024-03-28 12:12
    关注

    【以下回答由 GPT 生成】

    import threading
    import concurrent.futures
    
    json_data_object_lock = threading.Lock()
    pKmSFk8_lock = threading.Lock()
    
    def process_item(month):
        global json_data_object, pKmSFk8
    
        filed = request_data()
    
        with json_data_object_lock:
            json_data_object = {
                "city": "杭州",
                "month": month
            }
    
        with pKmSFk8_lock:
            pKmSFk8 = {
                "appId": "3c9208efcfb2f5b843eec8d96de6d48a",
                "method": "GETDAYDATA",
                "timestamp": filed.timestamp(),
                "clienttype": "WEB",
                "object": json_data_object,
                "secret": filed.secret()
            }
    
        time.sleep(1)
        main_sql()
    
    def main():
        new = selector()
        items = new.month_list()
    
        with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
            executor.map(process_item, items)
    

    通过在对共享资源访问时使用不同的锁(json_data_object_lock, pKmSFk8_lock),确保了对json_data_object和pKmSFk8的操作是线程安全的,从而解决了数据冲突问题。



    【相关推荐】



    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

问题事件

  • 创建了问题 3月28日

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算