You are on page 1of 2

BAKERY ALGORITHM

(22BCE1726)
JANAKI MADHAVA SAI TEJA
CODE :

#include <stdio.h>
#include <stdbool.h>
#include <pthread.h>
#include <stdint.h>
#define MAX_THREADS 100

bool choosing[MAX_THREADS];
int number[MAX_THREADS];

int maximum(int arr[], int size) {


int max_val = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max_val) {
max_val = arr[i];
}
}
return max_val;
}
void lock(intptr_t thread_id, int num_threads) {
choosing[thread_id] = true;
number[thread_id] = 1 + maximum(number, num_threads);
choosing[thread_id] = false;

for (intptr_t p = 0; p< num_threads; p++)


{
while (choosing[p]) {}
while ((number[p] != 0) && ((number[p] < number[thread_id]) ||((number[p] ==
number[thread_id]) && (p < thread_id)))) {}
}
}

void unlock(intptr_t thread_id)


{
number[thread_id] = 0;
}

void* thread_function(void* arg) {


intptr_t thread_id = (intptr_t)arg;
lock(thread_id, MAX_THREADS);
printf("Thread %ld is in the critical section.\n", (long)thread_id);
printf("Thread %ld is in the non-critical section.\n", (long)thread_id);
return NULL;
}
int main() {
int num_threads = 4;
pthread_t threads[MAX_THREADS];
intptr_t thread_ids[MAX_THREADS];
for (intptr_t i = 0; i < num_threads; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, thread_function, (void*)thread_ids[i]);
}
for (int i = 0; i < num_threads; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}

You might also like