สัญญาณเป็นแนวคิดของกระบวนการหรือการซิงโครไนซ์เธรด เราจะมาดูวิธีการใช้เซมาฟอร์ในโปรแกรมจริงกัน
ในระบบ Linux เราสามารถรับไลบรารีสัญญาณ POSIX หากต้องการใช้งาน เราต้องรวมไลบรารี semaphores.h เราต้องคอมไพล์โค้ดโดยใช้ตัวเลือกต่อไปนี้
gcc program_name.c –lpthread -lrt
เราสามารถใช้ sem_wait() เพื่อล็อคหรือรอ และ sem_post() เพื่อปลดล็อค สัญญาณเริ่มต้น sem_init() หรือ sem_open() สำหรับการสื่อสารระหว่างกระบวนการ (IPC)
ตัวอย่าง
#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$