Here is your basic problem. When you create a thread (regardless of OS) you have no guarantee that the thread will start immediately. So you have a loop that creates threads and passes a pointer to a local variable (
i
) and then you go on to change
i
without knowing if the thread started or not nor if it picked up the value of
i
or not.
So, given the vagueness of how operating systems schedule thread execution, it is possible for you to create all 10 threads, therefore the value of
i
would be 11 before *any* of the threads actually start so they would all have 11. In fact, just about any combination is possible.
You have the classic case of "I need the start of the threads to be synchronized but have done absolutely nothing to synchronize them". Thread synchronization does not happen by magic, you need to create events / semaphores and signal and wait on them properly to achieve synchronization.
Also, you are copying the "pointer to the argument" (
*arg
) and not the "value of the argument" so you are carrying around a pointer to
i
in
iValue
so even if they were properly synchronized, you'd still have each thread pointing to a variable that is changing.
<edit>
PS, I went and looked at the material you linked in. When you read about pthreads you obviously missed this section on creating threads and
Passing Argument.[
^]. You have actually implemented example 3 of that documents, the *wrong* way to pass values. You should have implemented example 1.