/Pthreads – I

Pthreads – I

POSIX Threads (phtread) [1]
————————

POSIX thread libraries are the standard thread API for C/C++ ,

as the name suggests it allows you to use threading which makes the exectution of your application faster

specially on multi-processor or multi-core systems where one process run on one processor while another one is running on the other , gains are also found on uniprocessor systems which exploit latency in I/O and other system functions which may halt process execution. (One thread may execute while
another is waiting for I/O or some other system latency.)

Note that all threads share the same address space of the main process ,so let’s hop on to the code explaination will be included in the comments

 

Now that you’ve read all that , what this code does is that it creates 2 different threads running the same function, waits for them to finish then prints their exit status and waves goodbye (here is the code without the comments : http://pastebin.com/X3qQDVrk << looks alot prettier on huh ? 😀 )
if you compile that using : gcc -o threads threads.c -lpthread
then run it ./threads
you should get this :
Thread 1 says hi!
Thread 2 says hi!
Thread 1 returns: 0
Thread 2 returns: 0
Perfect! now comment out the pthread_join lines and recompile and run then see what happens
Thread 1 says hi !
Thread 1 returns: 0
Thread 2 returns: 0
Uh..run again !
Thread 1 returns: 0
Thread 2 returns: 0
errr…
see the risk i told you about above ?
That’s enough for now We’ll continue this Next week isA 😉