Creating POSIX Threads

 [Previous Chapter]  [Previous Page]  [Contents]  [Next Page]  [Next Chapter]

ForkAndJoin.C
#include <pthread.h>
#include <iostream>

using namespace std;

extern "C" void* do_something(void* arg) {
   int number = *((int*) arg);
   cout << "Thread " << number << " does something." << endl;
   return arg;
} // do_something

int main() {
   const int THREADS = 10;
   pthread_t thread[THREADS];
   int args[THREADS];

   for (int i = 0; i < THREADS; ++i) {
      args[i] = i;
      if (pthread_create(&thread[i], 0, do_something,
            &args[i])) {
         cerr << "pthread_create failed, aborting!\n"
            << endl;
         exit(1);
      }
      cout << "Thread " << i << " started." << endl;
   }

   // ...
} // main

 [Previous Chapter]  [Previous Page]  [Contents]  [Next Page]  [Next Chapter]
Copyright © 2001, 2002 Andreas Borchert, converted to HTML on February 21, 2002