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 {
        defer self.mutex.unlock();;
    pub fn get(...) ... {
        defer self.mutex.unlock();