Thursday, 24 November 2011

multithreading sync

multithreading sync

Hello,

I am trying to write a program that will use multiple threads to sell tickets at the same time. don't know how to use the mutex to control that. The program compiles but the TICKETSOLD is more than the array size.


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <pthread.h>
#include <iostream>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <semaphore.h>
#include <fcntl.h>
using namespace std;

#define ARRAYSIZE 100
int TICKETSOLD=0;
int tickets[ARRAYSIZE];
int flag;
//char sem1[] = "/semBlock";
//sem_t *Scount;



pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;

void *work (void * arg); //function prototype


int main (int argc, char * argv[])
{
//FILE *fin;
time_t now;
//char lineBuf[LB_SIZE];
pthread_t tid; //structure that holds thread number
int childno, mainnum = 0, i, childcount, sum;
int *shared;
char *input;

if (argc == 2)
{
strcpy (input, argv[1]);
}
else
{
cout << "Usage: " << argv[0] << " Number of agents" << endl;
exit(1);
}

for (i = 0; i < ARRAYSIZE; i++) //Fill array with 0-49. Sum = 1225
tickets[i] = 0;

time (&now);
printf ("Thread test at %s\n", ctime(&now));
childcount= atoi (input);
childno = 1;
for (i = 0; i < ARRAYSIZE; i++)
{
cout << tickets[i] << " , ";
sum += tickets[i];
}
cout << "\nThe sum of all values is " << sum << endl;



while (childno <= childcount)
{
flag = 0;
if ((pthread_create (&tid, NULL, &work ,(void *)&childno))>0)
{
printf("Couldn't create new thread!\n");
exit(2);
} else //we're in main
{
while (flag == 0) ;
printf("Just created thread %d\n", tid);
childno++;

}
}

for (i = 0; i < ARRAYSIZE; i++)
{
cout << tickets[i] << " , ";
sum += tickets[i];
}
cout << "\nThe sum of all values is " << sum <<" "<<TICKETSOLD<< endl;
work(&mainnum);
for(i=0;i<childcount;i++)
pthread_join(tid,NULL);
printf ("Terminating Main program......\n");
return 0;
} //end of main

void *work(void * arg)
{
//Scount = sem_open(sem1, O_CREAT, 0666, 1);
//sem_close (Scount);

int i,j, childnum;
flag = 1;
childnum = *(int *) arg;

//Scount = sem_open(sem1, 0);

while(TICKETSOLD< ARRAYSIZE)
{
//sem_wait (Scount);
pthread_mutex_lock( &mutex1 );

int ticketSale = (rand() % 8+1);

for (j=0; j< ticketSale; j++)
{

//sem_wait (Scount);




while(tickets[TICKETSOLD]==1)
TICKETSOLD++;

tickets[TICKETSOLD]= 1;

TICKETSOLD++;

cout<<"sold "<< TICKETSOLD<<" by agent "<< childnum<<endl;





//agent[procNum]+=1;
//if(LOOPCOUNT%5==0)

}
//sem_post (Scount);
pthread_mutex_unlock( &mutex1 );



//cout << "agent " <<childnum<<" sold "<< ticketSale<<endl;

//if(TICKETSOLD%5==0)



}
//sem_close(Scount);



}

No comments:

Post a Comment