I have the following problem:
A lan house with 3 pcs, I will insert an X value in the terminal that will be the number of clients that arrive in the lan house, customers can only use the pcs that are unoccupied, if you are busy go to a waiting room, this waiting room supports 15 customers. If you do not have a spare PC or space in the waiting room, the customer simply leaves ...
1) Yes, it's a college job; 2) No, I do not want anything solved with a kissed hand; 3) I just need some help to understand how to solve this problem ....
I've read a lot about semaphore
, mutex
, threads
, but even so what needs to be done is still kind of obscure for me.
Here is the very few I wrote trying to solve this problem. Any tip is very welcome!
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define ROOM_SIZE 15
sem_t queue, pc;
int room [ROOM_SIZE]; // 0 -> livre | != 0 -> ocupado
int pcsAvaliable = 3, roomAvaliable = ROOM_SIZE;
int computers[3] = {0, 0, 0}; // 0 -> livre | 1 -> ocupado
struct Client{
int id;
};
int check_computer()
{
int i;
for(i=0; i<3; i++)
{
if(computers[i] == 0)
return i;
}
return -1;
}
void insert_waitingRoom(int idClient)
{
int i;
for(i=0; i< ROOM_SIZE; i++)
{
if(room[i] == 0)
room[i] = idClient;
}
}
void* Lan(void* arg)
{
struct Client *cli = (struct Client*) arg;
int idPC;
int idClient = cli->id;
if(pcsAvaliable > 0)
{
sem_wait(&pc);
pcsAvaliable--;
idPC = check_computer();
if(idPC >= 0)
{
computers[idPC] = 1;
printf("Cliente %d pegou pc %d\n", idClient, idPC);
usleep( ( (rand() % 11) + 80) * 1000);
computers[idPC] = 0;
printf("Cliente %d deixou o pc %d\n", idClient, idPC);
pcsAvaliable++;
}
sem_post(&pc);
sem_post(&queue);
}
else
{
//Quando os pcs estão ocupados, o cliente fica na sala de espera.
//Mas ele fica lá eternamente. Tem que fazer ele tentar entrar no PC e não o novo processo que vem da main.
if(roomAvaliable >0)
{
sem_wait(&queue);
roomAvaliable--;
printf("Cliente %d foi posto na sala de espera !\n", idClient);
insert_waitingRoom(idClient);
while(pcsAvaliable <= 0)
{
//tentar acessar pc
}
}
}
}
int main(int argc, char const *argv[])
{
int i=0, j=1;
if(argc > 1)
{
int numClients = atoi(argv[1]);
sem_init(&pc, 0, 3);
sem_init(&queue, 0, 15);
pthread_t clients[numClients];
//Create Clients
for(i=0; i< numClients; i++)
{
struct Client* cli = (struct Client*) malloc(sizeof(*cli));
cli->id = i;
pthread_create(&clients[i], NULL, Lan, (void*)cli);
usleep( ( (rand() % 5) + 1) * 10000);
}
}
else
printf("Por favor. Informe o número de clientes");
sem_destroy(&pc);
pthread_exit(NULL);
return 0;
}