Sunday, April 13, 2008

Pthreads

I needed to learn a little about pthreads so that I could modify some code for work. Below is a sample program that does some basic counting in threads. I've used pthread_join to wait for the threads to finish. I did this because I wanted to signal to the threads when to finish. There's a global value, thread_exit, that is shared with the threads. Setting thread_exit = true signals all of the threads to exit. It is set after the program sleeps for 1 second.

If a thread needs to do a certain amount of work and finish during it's own time, a status flag could be passed into the thread. When the thread is finished, the flag would be set. This method is described in the pthread_join man page.

Numerous examples demonstrating the use of pthreads can be found using google.

Put iostream and pthread.h between the <>.

//============================================================================
// Name : pthread_test.cpp
// Author : James Hubbard
// Version :
// Copyright : Public Domain
// Description : Pthread Example
//============================================================================

#include <>
#include <>


using namespace std;
bool thread_exit = false;

void *thread_test(void *arg) {
int thread_num = *((int *)arg);
int *count = new int(0); //clean up elsewhere
while (!thread_exit) {
(*count)++;
//if ( !(*count%5000000) )
// cout << "thread " << thread_num << ": " << *count << endl;
}
cout << "Thread " << thread_num << " complete: " << *count << endl;
return (void *)count;
}

int main() {
int num_threads = 10;
pthread_t *thread_id = new pthread_t[num_threads];

cout << "Pthread Test" << endl;
for (int i = 0; i < num_threads; i++) {
int error = pthread_create (&thread_id[i], NULL,
thread_test, (void *)&i);
if (error)
cout << "Error: " << error << endl;
}

sleep(1);
thread_exit = true;
int *count_value[num_threads];

for (int i = 0; i < num_threads; i++ )
pthread_join(thread_id[i], (void **)&count_value[i]);

cout << endl;
for (int i = 0; i < num_threads; i++) {
cout << "main count " << i << ": " << *count_value[i] << endl;
delete count_value[i]; //cleanup counts from threads
}

delete thread_id;

return 0;
}