Thursday, October 16, 2008

Multithread programming

Multi-threaded programs are a must in a world dominated by servers, GUI applications, multiprocessor computers and so on. The standard way of managing threads is by using POSIX threads. I've found and amazingly easy to follow article about POSIX threads. It's only recommendable for those of you who already have knowledge of the basic thread mechanisms and OS design:

Multi-Threaded Programming With POSIX Threads

Examples are written in plain old marvelous C, so it might be hard to understand for the Java, and C# crowd, but lads, this is real software!!! :)

Here you have a little example using threads, it's not rocket science, but makes the job:


#include
#include
#define LIMIT 100

/* prototype of the function that will be executed by a
thread. It's compulsory to return a void * and to receive
a void * as the only parameter */
void * do_loop(void * arg);


int main()
{
/* The thread to be created */
pthread_t MiThread;
/* We will use these two as parameters to do_loop */
int th1 = 1;
int th2 = 2;
/* Will get the return value of pthread_create(...) */
int rc;
printf("Starting application\n");
/* Actual thread creation. Parameters:
1st .- The thread to be initialized
2nd .- Configuration parameters, NULL to use default
3rd .- The function to be executed by the thread
4th .- The parameter to be passed to do_loop
*/
rc = pthread_create(&MiThread,NULL,do_loop,(void *)&th1);
/* The main thread also executes the loop, to show us the intermixed
execution of both threads */
do_loop((void*)&th2);
/* Just in case, the main thread waits for the auxiliary thread to
finish */
pthread_join(MiThread,NULL);
system("PAUSE");
}

void * do_loop(void * arg)
{
int i = 0;
for (i = 0 ; i < LIMIT ; i++)
printf("Hello Thread %d\n",*(int *)arg);
return NULL;
}



By the way, there is a companion article that gives an introduction to parallel programming. Interesting for the newbie.

Parallel Programming - Basic Theory For The Unwary

Enjoy!

Labels: , ,

0 Comentarios:

Post a Comment

<< Home