如何在 C 語言中使用 POSIX 訊號量


訊號量是一個程序或執行緒同步的概念。這裡我們將瞭解如何在真實的程式中使用訊號量。

在 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$

更新於: 2019 年 7 月 30 日

2K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.