Hi, i am writing this program to get myself started with posix thread.
I am expecting the program to output:
in main thread: i = 0
in child thread: i = 0 (maybe 1 here...the goal is to test shared variables in threads.)
However, the only output i see is
in main thread: i = 0
Why doesnt the child thread reach this if condition? if (pthread_equal(tid, mainThread) != 0)
How should i change the code to get the expected output?
The statement if (pthread_equal(tid, mainThread) != 0) never runs true anyway, You're checking to see if tid is equal to mainThread, but tid is a thread handle of your *thread function not the main thread, so it will never not be equal to 0 because pthread_equal(tid, mainThread) will always return false. That's why it does print in main thread: i = 0. You could change it so that the *thread function itself prints the value of i and make i's scope global; BUT that isn't thread safe and to make it thread safe you're going to have to use mutex's.