Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <thread.h>
void* servant( void* );
#define FALSE 0
#define TRUE 1
#define MAX 30
static int count;
static int list1[MAX];
static int list2[MAX];
/******************************************************************************
Function main
Initialize variables and create two additional threads, then wait for the
servant threads to complete.
******************************************************************************/
int main()
{
pthread_t mythread[2];
int i;
pthread_setconcurrency( 3 );
count = 0;
for (i=0; i<MAX; i++)
{
list1[i] = 0;
list2[i] = 0;
}
for (i=0; i<2; i++)
{
if (pthread_create( &mythread[i], NULL, servant, (void*) i ))
{
printf( "*** Error creating thread ***\n" );
exit( -1 );
}
}
for (i=0; i<2; i++)
{
if (pthread_join ( mythread[i], NULL ))
{
printf( "*** Error joining thread ***\n" );
exit( -2 );
}
}
printf( "\nFinal contents of arrays:\n\n" );
for (i=0; i<MAX; i++)
{
printf( " %2d: %d %d", i, list1[i], list2[i] );
if (list1[i] == 0 || list2[i] ==0 || list1[i] != list2[i])
{
printf( " *** error ***" );
}
printf( "\n" );
}
printf( "\nFinal value of count: %d\n\n", count );
return 0;
}
/******************************************************************************
Function servant
Each servant thread loops MAX times, incrementing the count by 1
and placing its thread ID into two parallel arrays.
******************************************************************************/
void* servant( void* arg )
{
pthread_t tid = pthread_self();
int i;
for (i=0; i<MAX; i++)
{
if (count < MAX)
{
list1[count] = tid;
if ((random()&0x00000003) == 0x00000003) thr_yield();
list2[count] = tid;
count = count + 1;
}
}
return NULL;
}
replacing thread.h(solaris) for sched.h and thr_yield(solaris) for sched_yield why the value of count comes to 31?