1. Better indentation - Indentation style - Wikipedia
Pick a style and stick to it.
In particular, do not mix spaces and tabs. Your code editor might make a decent job of it, but as soon as you post it / print it / give it to someone else who doesn't have your clever editor, it looks like dog food.
2. Better variable names.
Just how meaningless is var1 = 1 ?
Example
Code:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#define NUM_TOURISTS 5
enum locations {
AT_STATION,
TRAVEL_TO_CENTRE,
AT_CENTRE,
TRAVEL_TO_STATION,
};
const char *str_locations[] = {
"AT_STATION",
"TRAVEL_TO_CENTRE",
"AT_CENTRE",
"TRAVEL_TO_STATION"
};
enum locations bus_location = AT_STATION;
enum locations tourist_locations[NUM_TOURISTS] = {
AT_STATION,
AT_STATION,
AT_STATION,
AT_STATION,
AT_CENTRE
};
pthread_cond_t c_stopped = PTHREAD_COND_INITIALIZER;
pthread_mutex_t m_stopped = PTHREAD_MUTEX_INITIALIZER;
void *bus ( void *p ) {
while( 1 ) {
printf("Bus %s\n", str_locations[bus_location]);
if( bus_location == AT_CENTRE || bus_location == AT_STATION ) {
// tell all the passengers who might be waiting
pthread_cond_broadcast(&c_stopped);
}
sleep(2);
// go to the other stop
if ( bus_location == TRAVEL_TO_STATION ) {
// loop back to the beginning
bus_location = AT_STATION;
} else {
// on to the next stop
bus_location++;
}
}
return NULL;
}
void *tourist( void *p ) {
int id = (intptr_t)p;
printf("tourist %d waiting for bus at %s\n", id, str_locations[tourist_locations[id]]);
while( 1 ) {
pthread_mutex_lock(&m_stopped);
pthread_cond_wait(&c_stopped,&m_stopped);
// Bus just told us it reached a stop
if( tourist_locations[id] == bus_location ) {
printf("tourist %d using the bus\n", id);
}
pthread_mutex_unlock(&m_stopped);
sleep(1);
}
return NULL;
}
int main( ) {
pthread_t thread;
pthread_create(&thread, NULL, bus, NULL);
for(int i = 0 ; i < NUM_TOURISTS ; i++ ) {
pthread_create(&thread, NULL, tourist, (void*)(intptr_t)i);
}
pthread_exit(NULL);
}
$ ./a.out
Bus AT_STATION
tourist 0 waiting for bus at AT_STATION
tourist 1 waiting for bus at AT_STATION
tourist 2 waiting for bus at AT_STATION
tourist 3 waiting for bus at AT_STATION
tourist 4 waiting for bus at AT_CENTRE
Bus TRAVEL_TO_CENTRE
Bus AT_CENTRE
tourist 4 using the bus
Bus TRAVEL_TO_STATION
Bus AT_STATION
tourist 0 using the bus
tourist 1 using the bus
tourist 2 using the bus
tourist 3 using the bus
Bus TRAVEL_TO_CENTRE
Bus AT_CENTRE
tourist 4 using the bus
Bus TRAVEL_TO_STATION
Bus AT_STATION
tourist 0 using the bus
tourist 1 using the bus
tourist 2 using the bus
tourist 3 using the bus
Bus TRAVEL_TO_CENTRE
Bus AT_CENTRE
tourist 4 using the bus
Now all you need to do is when a tourist gets on the bus at the station, they get off the bus at the centre.