Untitled
unknown
plain_text
a year ago
2.0 kB
5
Indexable
#include <stdio.h> #include <pthread.h> #include <semaphore.h> // Global semaphore declarations sem_t sem1, sem2, sem3, sem4, sem5; void* printThread1(void* arg) { sem_wait(&sem5); // Wait for space thread to print spaces printf("EWU "); sem_post(&sem1); // Signal thread 2 to proceed pthread_exit(NULL); } void* printThread2(void* arg) { sem_wait(&sem1); // Wait for thread 1 to complete printf("is one of the "); sem_post(&sem2); // Signal thread 3 to proceed pthread_exit(NULL); } void* printThread3(void* arg) { sem_wait(&sem2); // Wait for thread 2 to complete printf("best universities in "); sem_post(&sem3); // Signal thread 4 to proceed pthread_exit(NULL); } void* printThread4(void* arg) { sem_wait(&sem3); // Wait for thread 3 to complete printf("Bangladesh\n"); sem_post(&sem4); // Signal thread 5 to proceed pthread_exit(NULL); } void* printSpaces(void* arg) { sem_post(&sem5); // Signal thread 1 to print "EWU" sem_wait(&sem4); // Wait for thread 4 to complete pthread_exit(NULL); } int main() { // Initialize semaphores sem_init(&sem1, 0, 0); sem_init(&sem2, 0, 0); sem_init(&sem3, 0, 0); sem_init(&sem4, 0, 0); sem_init(&sem5, 0, 0); // Thread declarations pthread_t thread1, thread2, thread3, thread4, spaceThread; // Create threads pthread_create(&thread1, NULL, printThread1, NULL); pthread_create(&thread2, NULL, printThread2, NULL); pthread_create(&thread3, NULL, printThread3, NULL); pthread_create(&thread4, NULL, printThread4, NULL); pthread_create(&spaceThread, NULL, printSpaces, NULL); // Wait for threads to finish pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); pthread_join(thread4, NULL); pthread_join(spaceThread, NULL); // Destroy semaphores sem_destroy(&sem1); sem_destroy(&sem2); sem_destroy(&sem3); sem_destroy(&sem4); sem_destroy(&sem5); return 0; }
Editor is loading...
Leave a Comment