Exemplo n.º 1
0
/* pre: takes in a void* 'n' which must be a pointer to an integer
 * post: create a producer thread
 */
void* producer(void *n)
{
    int number;
    struct s_product* prod;

    number = *((int*)n);

#ifdef DEBUG
    printf("[DEBUG]\tStarting producer [%d]\n", number);
    fflush(stdout);
#endif

    /* create products while we have not reached maxProductCount */
    while (gl_env.productCount < gl_env.maxProductCount)
    {
        /* lock on creating a product in order to be sure we have the correct
         * productCount
         */
        pthread_mutex_lock(&gl_env.create_prod_lock);

        /* check count again in case of weird scheduling */
        if (gl_env.productCount == gl_env.maxProductCount)
        {
            pthread_mutex_unlock(&gl_env.create_prod_lock);
            break;
        }
#ifdef DEBUG
        printf("[DEBUG]\tProducer [%d] producing product\n", number);
        fflush(stdout);
#endif
        prod = produceProduct();

        pthread_mutex_unlock(&gl_env.create_prod_lock);

        /* the queue handles critical sections itself */
        push_q(prod);

        printf("Producer %d has produced product %d\n", number, prod->id);
        fflush(stdout);

        /* usleep for 100 milliseconds */
        usleep(100000);
    }

    /* return NULL removes compiler warning */
    return NULL;
}
Exemplo n.º 2
0
// Producer code
void *producer(void *argument)
{
	int *prodNo = (int *) argument; // Producers identifying number
	Node *node; // Produced node
	
	while(1)
	{
		// Produce or stop
		int tw = sem_trywait(&products_remaining);
		if(tw == -1) // If there are no more products to be produced, end thread.
		{
			pthread_exit(0);
		}
		else if(tw == 0) // There are more products be produced.
		{	
			 node = produceProduct(); // Final product
		}
		else
		{
			printf("Some error occured when trying to wait on products_remaining semaphore");
		}
		
		// Add product to buffer
		sem_wait(&empty); // Wait for room in buffer.
		list_add(itemList, node); // Add node to list.
		
		// Increase count of number products in buffer.
		pthread_mutex_lock(&products_buffer_lock);
		products_in_buffer++;
		printf("Producer %d produced %s. Items in buffer: %d (out of %d) \n", *prodNo, node->elm, products_in_buffer, buffer_size);
		pthread_mutex_unlock(&products_buffer_lock);
		
		sem_post(&full); // Signal full so buffer space is decreased by 1.
		
		// Sleep for random time.
		sleepRandom(10000);
	}
}