如何使我的字典在Python中线程安全?

问题描述 投票:0回答:1

Python初学者。我有一个类如下,它维护历史记录的简单字典。它需要支持记录的插入和查找,即给定 ID 和年份,返回所有早于给定年份的记录。

请求是为了使其线程安全。假设会有很多线程同时调用 record 和 find_history,任何人都可以给我一些关于如何使字典线程安全的建议吗?

class Records:
    def __init__(self):
        self.map = {} # ID -> [year, location]

    def record(self, ID, year, location):
        if ID not in self.map:
            self.map[ID] = []
        self.map[ID].append([year, location])

    def find_history(self, ID, year):
        if ID not in self.map:
            return []
        results = []
        for record in self.map[ID]:
            if record[0] <= year:
                results.append(record)
        return results

非常感谢!

我尝试阅读Python多线程,仍然没有线索。

python multithreading
1个回答
0
投票

Python有提供Lock类的线程库。如果另一个线程已经获取了锁,锁的工作原理是阻止其他线程执行其代码。

您可以在执行某些操作之前使用 lock.acquire() ,然后在完成操作后使用 lock.release() 释放它。

import threading

class Records:
    def __init__(self):
        self.map = {} # ID -> [year, location]
        self.map_lock = threading.Lock() # <--- added this line

    def record(self, ID, year, location):
        with self.map_lock:  # <--- added this line
            if ID not in self.map:
                self.map[ID] = []
            self.map[ID].append([year, location])

    def find_history(self, ID, year):
        with self.map_lock:  # <--- added this line
            if ID not in self.map:
                return []
            results = []
            for record in self.map[ID]:
                if record[0] <= year:
                    results.append(record)
            return results
© www.soinside.com 2019 - 2024. All rights reserved.