CS FundamentalsModerateGATE CS · Amazon/Microsoft SDE MCQ

A program creates threads with `for (i = 0; i < 4; i++) pthread_create(&t[i], NULL, work, &i);` and each thread reads *arg as its index. What is the problem?

  1. A. pthread_create copies the value of i, so every thread just sees 0
  2. B. All threads get the same &i, so indices can repeat or even be 4
  3. C. The threads cannot start until the loop finishes, so all see 4 exactly
  4. D. Passing a pointer to a stack variable is rejected by the compiler

Correct answer: B. All threads get the same &i, so indices can repeat or even be 4

Every thread gets the same address, and the loop keeps changing i, so what a thread reads depends on timing: duplicates and the value 4 are possible. Pass a separate copy (an array element or heap value) per thread.

More Operating Systems questions

Exams that ask this topic