Lab Assignment-5_DOS(CSE3249) (1)
Lab Assignment-5_DOS(CSE3249) (1)
1. Producer-Consumer problem
Requirements:
CODE:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define BUFFER_SIZE 10
#define PRODUCER_ITERATIONS 20
#define CONSUMER_ITERATIONS 20
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
sem_t empty, full;
pthread_mutex_t mutex;
int main() {
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
pthread_join(prod_thread, NULL);
pthread_join(cons_thread, NULL);
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
OUTPUT:
2. Alternating Numbers with Two Threads
Problem: Write a program to print 1, 2, 3 … upto 20. Create threads where two threads print numbers
alternately.
Requirements:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_wait(&sem_a);
printf("%d\n", i);
sem_post(&sem_b);
return NULL;
sem_wait(&sem_b);
printf("%d\n", i);
sem_post(&sem_a);
return NULL;
int main() {
sem_init(&sem_a, 0, 1);
sem_init(&sem_b, 0, 0);
pthread_join(thread_a, NULL);
pthread_join(thread_b, NULL);
sem_destroy(&sem_a);
sem_destroy(&sem_b);
return 0;
OUTPUT:
3. Alternating Characters
Problem: Write a program to create two threads that print characters (A and B) alternately such as
ABABABABA…. upto 20. Use semaphores to synchronize the threads.
• Thread A prints A.
• Thread B prints B.
Requirements:
CODE:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_wait(&sem_a);
printf("A");
sem_post(&sem_b);
return NULL;
sem_wait(&sem_b);
printf("B");
sem_post(&sem_a);
return NULL;
int main() {
sem_init(&sem_a, 0, 1);
sem_init(&sem_b, 0, 0);
pthread_join(thread_a, NULL);
pthread_join(thread_b, NULL);
sem_destroy(&sem_a);
sem_destroy(&sem_b);
return 0;
OUTPUT:
Requirements:
CODE:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
printf("%d\n", i);
sem_post(&sem_b);
return NULL;
sem_wait(&sem_b);
printf("%d\n", i);
sem_post(&sem_a);
return NULL;
int main() {
sem_init(&sem_a, 0, 1);
sem_init(&sem_b, 0, 0);
pthread_join(thread_a, NULL);
pthread_join(thread_b, NULL);
sem_destroy(&sem_a);
sem_destroy(&sem_b);
return 0;
}
OUTPUT:
Problem: Write a program that creates three threads: Thread A, Thread B, and Thread C. The threads must print
numbers in the following sequence: A1, B2, C3, A4, B5, C6 … upto 20 numbers.
Requirements:
CODE:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t sem_a, sem_b, sem_c;
sem_wait(&sem_a);
printf("A%d\n", i);
sem_post(&sem_b);
return NULL;
sem_wait(&sem_b);
printf("B%d\n", i);
sem_post(&sem_c);
return NULL;
sem_wait(&sem_c);
printf("C%d\n", i);
sem_post(&sem_a);
return NULL;
int main() {
// Initialize semaphores
sem_init(&sem_a, 0, 1);
sem_init(&sem_b, 0, 0);
sem_init(&sem_c, 0, 0);
pthread_join(tA, NULL);
pthread_join(tB, NULL);
pthread_join(tC, NULL);
sem_destroy(&sem_a);
sem_destroy(&sem_b);
sem_destroy(&sem_c);
return 0;
OUTPUT: