Simple_threads2.c

/********************************************************
 * An example source module to accompany...
 *
 * "Using POSIX Threads: Programming with Pthreads"
 *     by Brad nichols, Dick Buttlar, Jackie Farrell
 *     O'Reilly & Associates, Inc.
 *
 ********************************************************
 * simple_threads.c
 *
 * Simple multi-threaded example.
 */
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
#include <errno.h>
#include <pthread.h>

void do_one_thing(int *);
void do_another_thing(int *);
void do_wrap_up(int, int);

int r1 = 0, r2 = 0;

void main()
{
  int i, n=20;
  
  pthread_t  *thread1, *thread2;

  thread1 = (pthread_t *) calloc(n, sizeof(pthread_t));

  thread2 = (pthread_t *) calloc(n, sizeof(pthread_t));


  for(i=0;i<20;i++){
  pthread_create(&(thread1[i]), 
	 NULL,
	 (void *) do_one_thing,
	 (void *) &r1);
	
  pthread_create(&(thread2[i]),
	 NULL, 
	 (void *) do_another_thing,
	 (void *) &r2); 
  }

  for(i=0;i<20;i++){
  pthread_join(thread1[i], NULL);
  pthread_join(thread2[i], NULL);
  }

  do_wrap_up(r1, r2);

  return; 
}

void do_one_thing(int *pnum_times)
{
  int i, j, x;
  
  for (i = 0;  i < 4; i++) {
    printf("doing one thing\n"); 
    for (j = 0; j < 10000000; j++) x = x + i;
    (*pnum_times)++;
  }

}

void do_another_thing(int *pnum_times)
{
  int i, j, x;
  
  for (i = 0;  i < 4; i++) {
    printf("doing another thing\n"); 
    for (j = 0; j < 10000000; j++) x = x + i;
    (*pnum_times)++;
  }

}


void do_wrap_up(int one_times, int another_times)
{
  int total;

  total = one_times + another_times;
  printf("All done, one thing %d, another %d for a total of %d\n",
	one_times, another_times, total);
}