Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C 언어에서 POSIX 세마포어를 사용하는 방법

<시간/>

세마포는 프로세스 또는 스레드 동기화의 개념입니다. 여기에서 실제 프로그램에서 세마포어를 사용하는 방법을 볼 것입니다.

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);
   //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$