सेमाफोर प्रक्रिया या थ्रेड सिंक्रोनाइज़ेशन की एक अवधारणा है। यहां हम देखेंगे कि वास्तविक कार्यक्रमों में सेमाफोर का उपयोग कैसे करें।
लिनक्स सिस्टम में, हम POSIX सेमाफोर लाइब्रेरी प्राप्त कर सकते हैं। इसका इस्तेमाल करने के लिए हमें semaphores.h लाइब्रेरी को शामिल करना होगा। हमें निम्नलिखित विकल्पों का उपयोग करके कोड को संकलित करना होगा।
gcc program_name.c –lpthread -lrt
हम लॉक या प्रतीक्षा करने के लिए sem_wait() का उपयोग कर सकते हैं। और sem_post() ताला जारी करने के लिए। सेमाफोर इंटर-प्रोसेस कम्युनिकेशन (आईपीसी) के लिए sem_init() या sem_open() को इनिशियलाइज़ करता है।
उदाहरण
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
sem_t mutex;
void* thread(void* arg) { //function which act like thread
sem_wait(&mutex); //wait state
printf("\nEntered into the Critical Section..\n");
sleep(3); //critical section
printf("\nCompleted...\n"); //comming out from Critical section
sem_post(&mutex);
}
main() {
sem_init(&mutex, 0, 1);
pthread_t th1,th2;
pthread_create(&th1,NULL,thread,NULL);
sleep(2);
pthread_create(&th2,NULL,thread,NULL);
//Join threads with the main thread
pthread_join(th1,NULL);
pthread_join(th2,NULL);
sem_destroy(&mutex);
} आउटपुट
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ gcc 1270.posix_semaphore.c -lpthread -lrt
1270.posix_semaphore.c:19:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
main() {
^~~~
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ ./a.out
Entered into the Critical Section..
Completed...
Entered into the Critical Section..
Completed...
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$