#include #include #include using namespace std; #include #include #define CHECK(x) \ { \ int res = x; \ if (res != 0) cerr << "PTHREAD ERROR: " << res << endl; \ } /** * data structure used to pass argument to thread * which contains the thread id */ typedef struct { int id; char msg[20]; } thread_data_t; /** * thread to execute */ void *thread_code(void *argument) { thread_data_t *data = (thread_data_t *) argument; int n_repeat = 5; while (n_repeat) { cout << "thread(" << pthread_self() <<") "; cout << ", id=" << data->id; cout << ", msg=[" << data->msg << "]"; cout << ", repeat=" << n_repeat << endl; --n_repeat; sleep(1); } } /** * Main function */ int main() { // array of threads pthread_t threads[10]; // array of data for threads thread_data_t data[10]; // create threads and data for (int i=0; i<10; ++i) { // initialize data for thread i data[i].id = i; sprintf(data[i].msg, "coucou %d", 100 + rand() % 100); // create thread i CHECK( pthread_create( &threads[i], NULL, thread_code, (void *) &data[i]) ); } cout << "!!! END OF PROGRAM !!!!" << endl; pthread_exit(NULL); return 0; }