如何在 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$
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP