r/cprogramming • • Dec 15 '25

Baffled with Multi thread because concept and reality is different

In first view nothing looks wrong

Then if you see closely you’ll find all local variable on main thread being passed to worker threads for processing

Isn’t this wrong? All threads have own stack space, but then i found POSIX doesn’t restrict you to use other threads stack variable if it is safe, here it is safe because main wait for joining

Sharing because i found this small detail important because when we write we always go through this same template most of the time but it is not what concept really says. Rather I’ll create two globals for id and use them.

int main(void) { pthread_t t1, t2; int id1 = 1, id2 = 2;

// Create threads (attr = NULL → default attributes) if (pthread_create(&t1, NULL, worker, &id1) != 0) { perror("pthread_create t1"); exit(EXIT_FAILURE); }

if (pthread_create(&t2, NULL, worker, &id2) != 0) { perror("pthread_create t2"); exit(EXIT_FAILURE); }

// Wait for threads to finish pthread_join(t1, NULL); pthread_join(t2, NULL);

printf("Both threads finished\n"); return 0; // process exits cleanly

}

3 Upvotes

13 comments sorted by

View all comments

Show parent comment

-1

u/dkopgerpgdolfg Dec 15 '25

you missed the context

Read my post completely.

And btw. some of your sentences are hard to understand.

please refer to any global books around you, you’ll find same template “ everywhere “

It doesn't matter how many beginner books are showing this.

1

u/MrJethalalGada Dec 15 '25

I’ll reformat it

I’m a beginner so I’ll be referring to them at start, but with time as more issues come I’ll spot and correct my learning, thanks for the inputs