Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- #include "sem.h"
- Semafor *sx = new Semafor(3);
- pthread_mutex_t most;
- int *sam;
- int n;
- int miastoA() {
- int x=0;
- for (int i=0;i<n;i++)
- if (sam[i]==0) x++;
- return x;
- }
- int miastoB() {
- int x=0;
- for (int i=0;i<n;i++)
- if (sam[i]==1) x++;
- return x;
- }
- int kolejkaA() {
- int x=0;
- for (int i=0;i<n;i++)
- if (sam[i]==2) x++;
- return x;
- }
- int kolejkaB() {
- int x=0;
- for (int i=0;i<n;i++)
- if (sam[i]==3) x++;
- return x;
- }
- int imost() {
- for (int i=0;i<n;i++) {
- if ((sam[i]==4) || (sam[i]==5)) return i;
- }
- return 0;
- }
- void msg() {
- printf("A-%d %d>>> [",miastoA(),kolejkaA());
- int i=imost();
- if (sam[i]==4) printf(">> %d >>",i+1);
- else printf("<< %d <<",i+1);
- printf("] <<<%d %d-B\n",kolejkaB(),miastoB());
- }
- void czekaj() {
- srand(time(NULL));
- sleep(rand()%15+3);
- }
- void *pmost(void * arg) {
- int s;
- s=(int)arg;
- while(1) {
- if ((sam[s]==0) || (sam[s]==1)) {
- czekaj();
- if (sam[s]==0) sam[s]=2;
- else sam[s]=3;
- }
- if ((sam[s]==2) || (sam[s]==3)) {
- sx->P();
- pthread_mutex_lock(&most);
- if (sam[s]==2) sam[s]=4;
- else sam[s]=5;
- //printf("Samochod nr %d przejezdza przez most.\n",s+1);
- msg();
- sleep(2);
- pthread_mutex_unlock(&most);
- if (sam[s]==4) sam[s]=0;
- else sam[s]=1;
- //printf("Samochod nr %d przejechal przez most.\n",s+1);
- //msg();
- sx->V();
- }
- }
- }
- int main(int argc, char * argv[]) {
- if (argc<2) {
- printf("Nie podales ilosci samochodow!\n");
- return -1;
- }
- n=atoi(argv[1]);
- int i;
- pthread_t thread[n];
- sam = new int [n];
- srand(time(NULL));
- for (i=0;i<n;i++)
- sam[i]=rand()%4;
- pthread_mutex_init(&most,NULL);
- for(i=0;i<n;i++)
- pthread_create(&thread[i],NULL,pmost,(void *)i);
- for(i=0;i<n;i++)
- pthread_join(thread[i],NULL);
- pthread_mutex_destroy(&most);
- delete sam;
- return 0;
- }
Add Comment
Please, Sign In to add comment