How to learn about mutexes and lock-free design?

I have shared resources that kind of look like this:

const BufferStatus = enum {
    available,
    in_use,
};

const Buffer = struct {
    buf: [1000]u8,
    status: BufferStatus = BufferStatus.available,

    pub fn use_this_buffer(self: *@This(), foo: u8) void {
        self.buf[0] = foo;
    }
};

var my_shared_resources: [16]Buffer = undefined;

Does anyone have resources I could reference for how to best implement locks or lock-free implementations for stuff?

1 Like

I’m not qualified to comment on writing a safe lock implementation, but the standard library does have a Mutex struct that might be worth looking at, specifically the SingleThreadedImpl:

Hope that helps!

1 Like

I also found some awesome videos by @dude_the_builder !

mutexes: https://www.youtube.com/watch?v=MnIM7nFPG88
atomics: https://www.youtube.com/watch?v=grMBeLJw7DM

4 Likes

Some resources:

6 Likes

Another good topic for basic thread safety mechanisms: Why `std.once`?

2 Likes

Lock-free design is one of those topics that is so tricky, the formal study in Computer Science is well-deserved. My recommendation here is to find a MOOC or textbook that goes over it, if you want to dive into that stuff.

7 Likes

I suggest Mark Batty’s thesis on the C/C++ concurrency model, chapter 3.

It’s not the easiest way to learn something if you are new to this topic, but it helped me to finally understand it. Chapter 3 gives a comprehensive definition of the memory model.

Although it is explained in the context of C/C++, mutexes and atomics are pretty much the same for all languages.

3 Likes

Some side note, about the usefulness:
In my current studies I came across these lock-free data structures. And even if they are locking really promising after some investigation, they are not that great. When you get to the point where you have to implement some kind of insert and remove operations, you get to a point where it becomes a huge pain.

And when you look at the performance benefits you get from using these no-lookup data structures, they are not that impressive.

From the paper I linked below, these are some measurements they came across.


artsync.pdf (tum.de) (I would not encourage you to read this - especially if you are new - this is more for reference).

Also, I would encourage you to look into opt. lock coupling if this is new to you.

3 Likes