During the good old DOS times, multithreading has been praticaly unknown but nowadays nearly every bigger project uses threads, these little nice "tasks" running independently from the main code. On multiprocessor machines there are really running parallel while this is in some way simulated on one-processor computer using task switching. Using threads under Unix system is implemented through the pthreads - POSIX threads - library.
After this little introduction on threads, let's dive into the actual code. I won't discuss all parts of the POSIX library like protecting shared memory but I will rather concentrate on the essential parts say creating and stopping a thread. For further information on threads, try googling as there are enough informations on that topic online.
When using threads in your project, you have to make sure that -lpthread is linked against your application. The main function to create a thread is pthread_create:
thread is a pointer to a pthread_t struct. attr can be used to set the properities of the thread but I will use the default settings, using 0. The third parameter is the startfunction that will be run in the thread declared as void* startfunction(void*). The last parameter is a void pointer that will be the first parameter of your startfunction.
Here's a little snippet creating two independent threads:
After compiling the application, you will have two threads running indepentendly from each other, one outputting 1 and the other 2. See how useful the fourth paramter is? ;-). To manually stop a thread, you can either use void pthread_exit(void *retval) from within the thread function or use one of these two functions:
The difference between the two is that pthread_join will wait until the thread has stopped and so stops the executing code while pthread_cancel sends a cancel request to the thread and immediately returns.
You should have noticed that using threads isn't difficult. After this code snippet you should have got enough knowledge to learn more about the more complex subjects like protecting shared memory. For the lazy fellows among us, try the SPosixThread class from code section. Questions? Message board. Happy Coding!