gallir

basic thread

Sep 29th, 2014
851
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5.  
  6. #define NUM_THREADS  2
  7. #define MAX_COUNT 100000000L
  8.  
  9. volatile long count = 0;
  10.  
  11. void *counter(void *threadid) {
  12.     long tid, i, max = MAX_COUNT/NUM_THREADS;
  13.     tid = (long)threadid;
  14.  
  15.     for (i=0; i < max; i++) {
  16.         count++;
  17.     }
  18.  
  19.     pthread_exit(NULL);
  20. }
  21.  
  22. int main (int argc, char *argv[]) {
  23.     pthread_t threads[NUM_THREADS];
  24.     int rc;
  25.     long t;
  26.  
  27.     for(t=0; t<NUM_THREADS; t++){
  28.         rc = pthread_create(&threads[t], NULL, counter, (void *)t);
  29.         if (rc){
  30.             printf("ERROR; return code from pthread_create() is %d\n", rc);
  31.             exit(-1);
  32.         }
  33.     }
  34.  
  35.     for(t=0; t<NUM_THREADS; t++){
  36.         pthread_join(threads[t], NULL);
  37.     }
  38.  
  39.     float error = (MAX_COUNT-count)/(float) MAX_COUNT *100;
  40.  
  41.     printf("Final result: %ld Expected: %ld Error: %3.2f%%\n", count, MAX_COUNT, error);
  42.  
  43.     puts("Bye from main");
  44.     pthread_exit(NULL);
  45. }
RAW Paste Data