This is a big question ^.^
When you have multiple threads (and you're running your program on a cpu with multiple cores) then those threads probably run parallel doing their stuff.
Especially they do memory requests. More especially - In the example above both threads use the global variable count.
Running this code you should run into run-time errors due to simultaneous count-variable access from both threads. It simply is not allowed that 2 Threads can read or write from/to the same memory space (in this example count).
This means to avoid those "fancy word: "race-conditions" " we have to make sure only one thread is allowed to access count at a certain time.
This leads to Mutexes.
With a Mutex a Thread accessing "count" can block all other Threads so they cannot do that at the same time.
Haven't used pthreads in a long time so Imma just show u in kinda "pseudo-code" in your example:
1 2 3 4 5 6 7 8 9 10 11 12
|
for(i = 0; i < NITER; i++)
{
"Mutex.lock" /*When a thread arrives here he "locks" this mutex
which means every other thread will wait here until it is "unlocked" */
// Then we do the following three lines without worrying another thread reads count as well
tmp = count;
tmp = tmp+1;
count = tmp;
"Mutex.unlock" /*Once our thread who arrived above first finished this "fancy word:"critcial region" "
we "unlock" the mutex which lets another Thread in obove at "Mutex.lock" */
}
|
Basicly all we do is we ensure that only one thread at a time is allowed to do
tmp = count;
tmp = tmp+1;
count = tmp;
More general: We only allowed one thread at a time to read/write from/to count - thus we don't get a run-time error
Semaphore is something similar to Mutex but that might be enough for now ;>
Now to your code: Once your main "Thread" (what you called "main process", that's not the right description, 'cause there is all the time just one process, but many threads (in your case at max 3) creates those 2 Threads they both will run simultaneously.
thread.join() simply means that at this point the "main Thread" is supposed to wait until the thread finished (yes we wait for thread1 first but thread2 is also running.)
I hope pthreads are automaticlly started when you "create" them. Sometimes you also have to call "thread.launch()" or something similar.
Well I probably forgot something - just keep asking ^.^