信号量是进程或线程同步的概念。在这里,我们将看到如何在实际程序中使用信号量。
在Linux系统中,我们可以获得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); //用主线程连接线程 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$