C11: Multi-threading and Anonymous structures
What you'll learn: How to use the C11 standard’s built-in support for concurrent execution and simplified data organization through anonymous structures.
Bringing Multi-threading to the Core
Before the C11 standard arrived, C didn’t officially "know" what a thread was. Programmers had to rely on external libraries like POSIX Threads (pthreads) on Linux or the Windows API. While these worked, they weren't part of the language itself.
C11 introduced <threads.h>, providing a standardized way to write concurrent code. Think of your program like a kitchen: without multi-threading, one chef must chop the onions, then boil the water, then sear the meat. With C11 threads, you can hire multiple chefs to work simultaneously, significantly speeding up the meal preparation. C11 provides thrd_create to start a task and mtx_init for "mutexes" (locks), which ensure two chefs don't try to use the same knife at the exact same time.
Anonymous Structures and Unions
C11 also introduced a "quality of life" feature called anonymous structures and unions. Previously, if you nested a struct inside another, you had to give it a name, leading to long, clunky access chains like player.position.coords.x.
Anonymous structures allow you to nest data without the extra name. It’s like having a dedicated "Spice Drawer" inside a "Cabinet." You don't have to open the "Cabinet," then the "Spice Drawer Label," then the "Cinnamon"; you just reach into the Cabinet and grab the Cinnamon directly.
Putting it Together
Here is how these C11 features look in practice:
#include <stdio.h>
#include <threads.h>
// A struct using an anonymous union
struct Gadget {
int id;
union { // No name here!
float weight;
int count;
};
};
int task(void *arg) {
struct Gadget *g = (struct Gadget*)arg;
printf("Thread working on Gadget ID: %d\n", g->id);
return 0;
}
int main() {
thrd_t thread_id;
struct Gadget my_gadget = { .id = 101, .count = 5 };
// Notice we access .count directly, not .union_name.count
printf("Main: Gadget count is %d\n", my_gadget.count);
// Starting a standardized C11 thread
if (thrd_create(&thread_id, task, &my_gadget) == thrd_success) {
thrd_join(thread_id, NULL);
}
return 0;
}
Key takeaway
C11 modernized the language by making multi-threading a native feature and simplifying data access through nested, nameless structures.