কম্পিউটার

সি ভাষায় POSIX সেমাফোর কীভাবে ব্যবহার করবেন


সেমাফোর হল প্রক্রিয়া বা থ্রেড সিঙ্ক্রোনাইজেশনের একটি ধারণা। এখানে আমরা দেখব কিভাবে বাস্তব প্রোগ্রামে সেমাফোর ব্যবহার করতে হয়।

লিনাক্স সিস্টেমে, আমরা POSIX সেমাফোর লাইব্রেরি পেতে পারি। এটি ব্যবহার করার জন্য, আমাদের semaphores.h লাইব্রেরি অন্তর্ভুক্ত করতে হবে। আমাদের নিম্নলিখিত বিকল্পগুলি ব্যবহার করে কোড কম্পাইল করতে হবে।

gcc program_name.c –lpthread -lrt

আমরা লক বা অপেক্ষা করতে sem_wait() ব্যবহার করতে পারি। এবং sem_post() লকটি ছেড়ে দিতে। সেমাফোর ইন্টার-প্রসেস কমিউনিকেশন (IPC) এর জন্য 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$

  1. একটি ভিন্ন ভাষায় ভয়েসওভার ব্যবহার করতে চান? এটি কীভাবে পরিবর্তন করবেন তা এখানে

  2. Tkinter Python এ থ্রেড কিভাবে ব্যবহার করবেন?

  3. গুগল শীটে গুগল ট্রান্সলেট কীভাবে ব্যবহার করবেন

  4. রুবি থ্রেডগুলি কীভাবে ব্যবহার করবেন:টিউটোরিয়াল বোঝার জন্য সহজ