Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #define DESK_SIZE 2
- #define LOW_SECONDS 2
- #define HIGH_SECONDS 6
- #define DEFAULT_N 10
- #define DEFAULT_K 4
- struct shared_data
- {
- unsigned n;
- unsigned k;
- volatile unsigned* desk;
- volatile unsigned current;
- volatile unsigned customer_id;
- pthread_mutex_t* mutex;
- pthread_cond_t* condBaker;
- pthread_cond_t* condCustomers;
- };
- void* bakerFunction(void* tdata)
- {
- struct shared_data* data = (struct shared_data*) tdata;
- int i = 0;
- while (i < data->n)
- {
- while (data->current == DESK_SIZE)
- {
- pthread_cond_wait(data->condBaker, data->mutex);
- }
- // Wait during baking time
- printf("Start of baking bread #%d\n", i + 1);
- sleep(DEFAULT_K);
- printf("End of baking bread #%d\n", i + 1);
- pthread_mutex_lock(data->mutex);
- data->desk[data->current++] = 1;
- printf("Putting a bread #%d on the desk\n", i + 1);
- i++;
- pthread_cond_broadcast(data->condCustomers);
- pthread_mutex_unlock(data->mutex);
- }
- }
- void customerWaiting()
- {
- unsigned divider = HIGH_SECONDS - LOW_SECONDS + 1;
- unsigned seconds = rand() % divider + LOW_SECONDS;
- sleep(seconds);
- }
- void* customerFunction(void* tdata)
- {
- struct shared_data* data = (struct shared_data*) tdata;
- pthread_mutex_lock(data->mutex);
- unsigned customer_id = data->customer_id++;
- pthread_mutex_unlock(data->mutex);
- printf("Customer #%u start waiting in bakery\n", customer_id);
- customerWaiting();
- pthread_mutex_lock(data->mutex);
- while (data->current == 0)
- {
- pthread_cond_wait(data->condCustomers, data->mutex);
- }
- printf("Customer #%u grab a bread from the desk\n", customer_id);
- data->current--;
- pthread_cond_signal(data->condBaker);
- pthread_mutex_unlock(data->mutex);
- printf("Customer #%u left a bakery\n", customer_id);
- return NULL;
- }
- int main(int argc, char** argv)
- {
- pthread_mutex_t mutex;
- pthread_mutex_init(&mutex, NULL);
- pthread_cond_t condBaker;
- pthread_cond_init(&condBaker, NULL);
- pthread_cond_t condCustomers;
- pthread_cond_init(&condCustomers, NULL);
- struct shared_data data = {
- DEFAULT_N,
- DEFAULT_K,
- (unsigned*) malloc(DESK_SIZE * sizeof(unsigned)),
- 0,
- 1,
- &mutex,
- &condBaker,
- &condCustomers
- };
- pthread_t customerThreads[DEFAULT_N];
- for (int i = 0; i < DEFAULT_N; i++)
- {
- pthread_create(&customerThreads[i], NULL, &customerFunction, &data);
- }
- pthread_t bakerThread;
- pthread_create(&bakerThread, NULL, &bakerFunction, &data);
- for (int i = 0; i < DEFAULT_N; i++)
- {
- pthread_join(customerThreads[i], NULL);
- }
- pthread_join(bakerThread, NULL);
- pthread_cond_destroy(&condCustomers);
- pthread_cond_destroy(&condBaker);
- pthread_mutex_destroy(&mutex);
- free((void*) data.desk);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement