Cum se scrie un program C pentru a Beta Parcare în limbajul de programare C ?
Solution:
- /* parcare beta */
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include </usr/include/semaphore.h>
- #define BUFF_SIZE 5
- #define NR_MASINI 5
- typedef struct{
- int buf[BUFF_SIZE];
- int in;
- int out;
- sem_t full;
- sem_t empty;
- pthread_mutex_t mutex;
- }parcare;
- parcare p;
- void* MasinaIn(void*arg)
- {
- int index = (int)arg;
- int item,i;
- for (i=0; i < 20; i++)
- {
- item =i;
- sem_wait(&p.empty);
- pthread_mutex_lock(&p.mutex);
- p.buf[p.in] = item;
- p.in = (p.in+1)%BUFF_SIZE;
- printf("\nEste parcata masina pe pozitia %d",index);
- fflush(stdout);
- pthread_mutex_unlock(&p.mutex);
- /* Increment the number of full slots */
- sem_post(&p.full);
- }
- return NULL;
- }
- void* MasinaOut(void* arg)
- {
- int i, item, index;
- index = (int)arg;
- for (i=20; i > 0; i--) {
- int r = rand() % 10;
- sem_wait(&p.full);
- pthread_mutex_lock(&p.mutex);
- item=i;
- item=p.buf[p.out];
- p.out = (p.out+1)%BUFF_SIZE;
- sleep(r);
- printf("\nA iesit masina de pe pozitia %d si a stat %d secunde in parcare\n", index,r);
- fflush(stdout);
- /* Release the buffer */
- pthread_mutex_unlock(&p.mutex);
- /* Increment the number of full slots */
- sem_post(&p.empty);
- /* Interleave producer and consumer execution */
- }
- return NULL;
- }
- int main(void)
- {
- pthread_t idMin, idMout;
- int index;
- sem_init(&p.full, 0, 0);
- sem_init(&p.empty, 0, BUFF_SIZE);
- pthread_mutex_init(&p.mutex, NULL);
- for (index = 0; index < 15; index++)
- {
- /* Create a new producer */
- pthread_create(&idMin, NULL, MasinaIn, (void*)index);
- }
- /*create a new Consumer*/
- for(index=0; index<5; index++)
- {
- pthread_create(&idMout, NULL, MasinaOut, (void*)index);
- }
- pthread_exit(NULL);
- }