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;
}
No comments:
Post a Comment