#include <stdio.h>
#include <pthread.h>

#define NUM_THREADS 50

int sum;
pthread_mutex_t mutex;

void* thread_routine(void* data)
{
   int i;
   int* blah = (int* )data;
   // printf("I am thread %d\n", *blah);

   for (i = 0; i < *blah*1000; i++)
   {
   // putting  lock in the loop makes this much slower but more 
   // interesting 
      pthread_mutex_lock(&mutex);

   // Or you can do... (faster in this case)
   //      while (pthread_mutex_trylock(&mutex));
      sum++;
      pthread_mutex_unlock(&mutex);
   }
   pthread_exit(NULL);
}


int main(void)
{
   int i;
   int data[NUM_THREADS];
   void* status;

   pthread_t t[NUM_THREADS];
   pthread_attr_t attr;


   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

   pthread_mutex_init(&mutex, NULL);

   for (i = 0; i < NUM_THREADS; i++)
   {  data[i] = i;
      pthread_create(&t[i], NULL, thread_routine, (void*) &data[i]);

   }

   for (i = 0; i < NUM_THREADS; i++)
   {  pthread_join(t[i], &status);
   }
   printf("SUM: %d\n", sum);

   pthread_mutex_destroy(&mutex);
   return 0;
}
Topic revision: r1 - 29 Sep 2008 - MattWalsh
 
This site is powered by the TWiki collaboration platformCopyright © 2008-2012 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback