Is there a safe way to use ArrayHashMap from different threads?

I’ve written some program, that catches and sends messages, with a few threads.
I need to share somehow ArrayHashMap between them.
Please, can someone give example how to use it with threads?
I have main thread, that must create ArrayHashMap and two threads, one consume and one produce data.

1 Like

You can use Mutex.
The mutex ensures that every operation you do between Mutex.lock and Mutex.unlock is exclusive and has no data races with other threads.

If you want to be extra fancy you can also make a wrapper struct like this:

const ThreadSafeHashMap = struct {
    map: HashMap(...),
    mutex: std.Thread.Mutex = .{},
    pub fn init(...)...{...}
    pub fn deinit...
    pub fn put(...) void {
        self.mutex.lock();
        defer self.mutex.unlock();
        self.map.put(...);
    }
    pub fn get(...) ... {
        self.mutex.lock();
        defer self.mutex.unlock();
        return self.map.get(...);
    }
};
4 Likes