Ejemplo n.º 1
0
void * generators(void *threadid)
{
   long tid;
   tid = (long)threadid;

   printf("Hello World! It's me, generator_thread #%ld!\n", tid);
   while(true)//for (int i=0; i<10; i++)//change to while(true)
   {
        pthread_mutex_lock(&mutex_pause);
        while (isPaused == 1)
        {
            pthread_cond_wait(&cond_pause, &mutex_pause);
        }
        //else
        //{
            pthread_mutex_unlock(&mutex_pause);
        //int rand_time=rand() % 10000;
        //usleep(rand_time);
        pthread_mutex_lock(&M);//lock mutex


        //critical section
        int material=tid;
        if ((!fix_buffer.check(tid)) || (!fix_buffer.check_buffer(material)) || (fix_buffer.size() >=10) )
        {
            dead_count++;
            cout<<"Deadlock due to full or too many of the material in the buffer!!!"<<endl;
            cout<<"Number of deadlock happened is "<<dead_count<<endl;
        }
        while ((!fix_buffer.check(tid)) || (!fix_buffer.check_buffer(material)) || (fix_buffer.size() >=10) )//check if there are many of those products
        if (pthread_cond_wait (&C, &M))//producer of the material goes to wait
        {
          fprintf (stdout, "pthread_cond_wait: producer\n");
          exit (-1);
        }
        /*int material=tid;
        while(!fix_buffer.check_buffer(material))// wait if the difference are 10
        if (pthread_cond_wait (&C, &M))
        {
            fprintf (stdout, "pthread_cond_wait: consumer\n");
            exit (-1);
        }*/

        printf(" thread #%ld produces %ld\n", tid, material);

        if (fix_buffer.size() >= 10)
        {
            cout<<"Full Wait"<<endl;

        }
        /*while (fix_buffer.size() >=10)//if its full wait
        if (pthread_cond_wait ( &C1 , &M))
        {
          fprintf (stdout, "pthread_cond_wait: producer\n");
          exit (-1);
        }*/
        fix_buffer.enqueue(material);
        //pthread_cond_signal (&C1);
        if (material==1)
        material1_count++;
        else if (material==2)
        material2_count++;
        else
        material3_count++;
        cout<<"current size of fix_buffer is "<<fix_buffer.size()<<endl;
        fix_buffer.show();
        cout<<material1_count<<" of material 1 are generated\n";
        cout<<material2_count<<" of material 2 are generated\n";
        cout<<material3_count<<" of material 3 are generated\n";
        pthread_mutex_unlock (&M);

        // noncritical section
        pthread_cond_signal (&C1);
    }
    //}
    pthread_exit(NULL);
}