如何在 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$
广告