Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #define POCET_PISOMIEK 68
- #define MAX_OPRAVIT 5
- #define PISOMKY_MIN 0
- #define PISOMKY_MAX 30
- #define POTREBNE_BODY 18
- struct thread_data
- {
- volatile unsigned* pisomky;
- volatile unsigned uspesnych;
- volatile unsigned current;
- volatile unsigned index;
- pthread_mutex_t* mutex;
- pthread_cond_t* cond;
- };
- void* generuj_pisomky(void* tdata)
- {
- struct thread_data* data = (struct thread_data*) tdata;
- printf("ZACIATOK GENEROVANIE PISOMIEK\n");
- pthread_mutex_lock(data->mutex);
- unsigned pocet_uspesnych = data->uspesnych;
- pthread_mutex_unlock(data->mutex);
- unsigned i = 0;
- while (pocet_uspesnych < 20 && i < POCET_PISOMIEK)
- {
- unsigned delitel = PISOMKY_MAX - PISOMKY_MIN + 1;
- unsigned pisomka = rand() % delitel + PISOMKY_MIN;
- pthread_mutex_lock(data->mutex);
- if (data->index < MAX_OPRAVIT)
- {
- data->pisomky[data->index++] = pisomka;
- data->current = ++i;
- pthread_cond_signal(data->cond);
- printf("Vygenerovana pisomka s %u bodmi\n", pisomka);
- }
- pocet_uspesnych = data->uspesnych;
- pthread_mutex_unlock(data->mutex);
- }
- printf("KONIEC GENEROVANIE PISOMIEK\n");
- return NULL;
- }
- void* opravuj_pisomky(void* tdata)
- {
- struct thread_data* data = (struct thread_data*) tdata;
- printf("ZACIATOK OPRAVOVANIA PISOMIEK\n");
- pthread_mutex_lock(data->mutex);
- unsigned pocet_uspesnych = data->uspesnych;
- pthread_mutex_unlock(data->mutex);
- unsigned i = 0;
- while (pocet_uspesnych < 20 && i < POCET_PISOMIEK)
- {
- pthread_mutex_lock(data->mutex);
- while (i == data->current)
- {
- pthread_cond_wait(data->cond, data->mutex);
- }
- unsigned pisomka = data->pisomky[--data->index];
- pthread_mutex_unlock(data->mutex);
- if (pisomka > POTREBNE_BODY)
- {
- pthread_mutex_lock(data->mutex);
- data->uspesnych = ++pocet_uspesnych;
- pthread_mutex_unlock(data->mutex);
- printf("Uspesna pisomka s %u bodmi\n", pisomka);
- }
- i++;
- }
- printf("KONIEC OPRAVOVANIA PISOMIEK\n");
- return NULL;
- }
- int main(int argc, char** argv)
- {
- pthread_mutex_t mutex;
- pthread_mutex_init(&mutex, NULL);
- pthread_cond_t cond;
- pthread_cond_init(&cond, NULL);
- struct thread_data data = {
- (unsigned*) malloc(MAX_OPRAVIT * sizeof(unsigned)),
- 0,
- 0,
- 0,
- &mutex,
- &cond
- };
- pthread_t thread_generuj;
- pthread_create(&thread_generuj, NULL, &generuj_pisomky, &data);
- pthread_t thread_opravuj;
- pthread_create(&thread_opravuj, NULL, &opravuj_pisomky, &data);
- pthread_join(thread_generuj, NULL);
- pthread_join(thread_opravuj, NULL);
- pthread_cond_destroy(&cond);
- pthread_mutex_destroy(&mutex);
- //free((void*) data.pisomky);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement