r/cprogramming • u/Appropriate-Scene-95 • Jun 21 '26
C11 Threads saving own memory state problem
So I want to implement a "non failing" malloc which should be thread safe (with c11 threads). Each thread will have it's own memory state (to avoid blocking). However I don't know how to accomplish that. My first idea was to have the memory states to be in an array and each thread id correspond to the index, but it seems like the c11 threads don't have that (at least the id is not necessarily numeric). My second idea was to use thread specific storage pointer, however one gets a key on creation of the thread, meaning two threads could get different keys to the same struct. Is there something you could recommend to me. I don't want to pass into my malloc the thread id.
Edit: I think it's solved, I was wrong thread_local (since c23) exists and _Thread_local (until c23) and not both (until c23)
5
u/FISHARM1 Jun 21 '26
Thread local is a keyword in c++ and also in C it appears: link
1
u/Defiant_Direction_54 Jun 21 '26
Hello, C programming noob here, learnt to use mutexes recently to avoid race conditions across threads. Would that be applicable to your problem or is that what you're trying to avoid?
.ie mention of avoiding blocking?
1
u/thank_burdell Jun 21 '26
It kind of depends what you’re trying to do. Is this just internal memory each thread needs to accomplish some task? Then have each thread allocate what it needs for itself, and free it before the thread returns.
If it’s some memory the main process needs to set up and initialize for each thread before they run, have the main process set that up initially, pass the corresponding portion to each thread, and free it when the threads return.
If it needs to be bidirectional communication between main and the created threads, the second approach will work for that too.
1
u/Pepedroni Jun 21 '26
Request memory using virtual memory directly from the OS instead of the stdlib, store the pages on the local storage of the thread. See mmap on *nix or virtualalloc in windows.
1
u/Low_Lawyer_5684 Jun 23 '26
Looks like you need a per-thread vars. Google _Thread_local keyword in C11