Edit: I think I am doing something wrong, because when I compile and run my binary twice, I get different outputs.
I am trying to understand flows with pthread, so I made a little code to simulate the passage of a train on a bridge (which can only handle 2 trains at a time)
I managed to do this so that only one train crosses the bridge at a time with this code:
#include <pthread.h>
#include <stdio.h>
#include <time.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *train()
{
int km;
static int t = 0;
km = 1;
while (km != 10)
{
printf("I'm at %02d km\n", km++);
sleep(1);
if (km == 2)
pthread_mutex_lock(&mutex);
if (km == 4)
pthread_mutex_unlock(&mutex);
}
}
int main()
{
pthread_t train1;
pthread_t train2;
pthread_t train3;
pthread_create(&train1, NULL, train, NULL);
pthread_create(&train2, NULL, train, NULL);
pthread_create(&train3, NULL, train, NULL);
pthread_join(train1, NULL);
pthread_join(train2, NULL);
pthread_join(train3, NULL);
}
This worked fine (or maybe I did something wrong, if so, please tell me)
And then I tried for the case when 2 trains can simultaneously pass over the bridge.
#include <pthread.h>
#include <stdio.h>
#include <time.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *train()
{
int km;
static int t = 0;
km = 1;
while (km != 30)
{
printf("I'm at %02d km\n", km++);
sleep(1);
if (km == 2 && t <= 2)
{
++t;
pthread_mutex_lock(&mutex);
}
if (km == 4)
{
t--;
pthread_mutex_unlock(&mutex);
}
}
}
int main()
{
pthread_t train1;
pthread_t train2;
pthread_t train3;
pthread_t train4;
pthread_create(&train1, NULL, train, NULL);
pthread_create(&train2, NULL, train, NULL);
pthread_create(&train3, NULL, train, NULL);
pthread_create(&train4, NULL, train, NULL);
pthread_join(train1, NULL);
pthread_join(train2, NULL);
pthread_join(train3, NULL);
pthread_join(train4, NULL);
}
So, I used a static int to “pop up” my train to 2 on the bridge, but it actually doesn't work, and I don't understand why ..
4- , 2 , 2 , 2- , , ..
-, , 4- , 2 , 2 , 2 , 2 .
, , .
!