Tuesday, June 22, 2010

pthread: basic threading - creating, waiting for and ending threads

Here is basic example program demonstrating threads using the posfix threads library.

The key points are;
  • Threads are created with a call to pthread_create, the parameters are:
    • The threads handle, consider it to be the equivalent of a file handle.
    • The threads attributes. Normally the defaults are sufficient so use NULL, otherwise you might end up having to allocate the stack for it too.
    • The function pointer to the threads "main", if this routine exits or returns it will implicitly end the thread just like the pthread_exit call.
    • And a generic chunk of memory that is passed to the threads "main".
  • pthread_join; this takes the threads handle and simply blocks until it gets the signal that the thread has ended. The second parameter is a pointer to the location of where to store the pointer for the threads exit.. gezz look at the function definition its more easy to understand than a written description of it.
  • pthread_exit: This is the thread equivalent of exit but it can return a pointer to a complex piece of data.

And here is the sample code its really simple and just a brush up on threads for now
//complie with; g++ thread.cpp -lpthread
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

struct BaseA
{
 pthread_t handler; //the handle to the thread.. a little dangerous!
 int number;
};

//The thread core...
void* thread_worker( void *ptr )
{
 BaseA *data = (BaseA*)ptr;

 for(int i = 0; i < 10; i++)
   {
     printf("Thread %d @ %d \n", data->number, i);
     sleep(rand()%3000/1000);
   }

 printf("Thread %d DONE!\n", data->number);
 pthread_exit(NULL);
}

int main()
{
 srand(time(NULL));

 BaseA data[2];

 //setup the threads
 data[0].number = 1;
 data[1].number = 2;

 // create the threads
 pthread_create (&data[0].handler, NULL, &thread_worker, (void *) &data[0]);
 pthread_create (&data[1].handler, NULL, &thread_worker, (void *) &data[1]);

 //wait for all kids to complete
 pthread_join(data[0].handler, NULL);
 pthread_join(data[1].handler, NULL);

 exit(0);
}

No comments:

Post a Comment