1

I'm thinking about how I would theoretically implement a multi threaded queue from first principles, using only glibc on POSIX.

Obviously, this is going to require a mutex (or some other locking/synchronization structure) internally, which is used by callers to get exclusive access to the internal data structure (linked list, or vector).

However, when writing this in C, there's the obvious implementation footgun: What if I access the internal structure without acquiring the lock?

In thinking of a solution, I considered the design where there's some sort of context structure containing the mutices, and their corresponding data structures:

struct custom_queue {
  struct queue_storage_ details;
  mutex_t details_mutex; // SOME ATTRIBUTE ("details") HERE
} context;

This way, the programmer could give the compiler some information about under what circumstances the field details should be accessed, eg only when details_mutex is locked. There could be different flavors of this attribute, to make sure you only operate on details, or maybe you're allowed to do other stuff too.

Of course, this would be less feasible for implementers if you stored the mutex in a separate struct or in some struct nested below/above details, so it probably would only support these checks if the mutex and the thing it locks are in the same structure.

This could in theory allow the compiler to give you warnings or errors when you use the mutex incorrectly, or remind you to lock it if you forgot, all at compile time.

Is there such a feature?

5
  • No, do you think that C knows anything about mutexes Commented Jan 23, 2024 at 8:39
  • 1
    Do you think that C knows anything about destructors, no-discard, or any of the myriad other non-standard attribute-based extensions available with GCC/Clang? Commented Jan 23, 2024 at 13:33
  • They are part of language extensions related to compilation. Mutex and member protected is much more abstract Commented Jan 23, 2024 at 15:40
  • 1
    If the answer is "no" and there's a relevant bit of documentation about the abstractions provided by the compiler, feel free to post it! Commented Jan 23, 2024 at 16:38
  • 1
    I don't think even MSVC's SAL (which does have markings for functions that take take/release a mutex) knows anything about what data the mutex covers. Commented Jan 24, 2024 at 2:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.