79690418

Date: 2025-07-04 15:49:40
Score: 1.5
Natty:
Report link

Great question! Understanding POSIX threads (pthreads) can be tricky at first, especially when you're still getting comfortable with pointers and how function arguments work in C.

Let's break down the code and explain what's happening step-by-step.

What does void *add(void *p_in) mean?

Inside the add function:

pair_t *p = (pair_t *)p_in;

What happens in adder(int x, int y)?

Yes, the thread arguments are passed to the add function via the last argument to pthread_create().

What's wrong with this code?

The main issue here is the lifetime of the pair_t p variable passed to the thread.


How to fix it?

To ensure the data passed to the thread remains valid until the thread finishes, you should dynamically allocate the pair_t struct on the heap, like this:

void adder(int x, int y) {
    pthread_t t;
    pair_t *p = malloc(sizeof(pair_t));  // allocate memory on heap
    p->a = x;
    p->b = y;
    pthread_create(&t, NULL, add, (void *)p);
    pthread_detach(t);  // detach thread if you don't want to join later
}

Also, inside the add function, after using p, free the allocated memory:

void *add(void *p_in) {
    pair_t *p = (pair_t *)p_in;
    printf("Answer is: %d\n", p->a + p->b);
    free(p);  // free heap memory to avoid memory leak
    return NULL;
}

For a complete beginner-friendly guide to POSIX threads, including examples, synchronization primitives like mutexes and condition variables, and debugging tips, check out this detailed tutorial on Embedded Prep:

🔗 POSIX Threads (pthreads) Beginner's Guide in C/C++


Reasons:
  • RegEx Blacklisted phrase (1.5): How to fix it?
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: nishant singh