Home  >  Article  >  Operation and Maintenance  >  Detailed explanation of various types of semaphores in Linux

Detailed explanation of various types of semaphores in Linux

PHP中文网
PHP中文网Original
2017-06-21 13:58:513597browse

Definition: Protect shared resources so that only one process (thread) owns the resource at a time

Principle: When the semaphore value is positive, it means it is idle, if it is 0 or negative, it means it is occupied

Classification: kernel semaphore and user semaphore. User semaphore is divided into POXIS semaphore and SYSTEMV semaphore. POXIS semaphore is divided into named semaphore and unnamed semaphore.

Kernel semaphore:

  • #include

  • void sema_init(struct semaphore *sem, int val);

  • void init_MUTEX(struct semaphore *sem); //Initial value 1

  • void init_MUTEX_LOCKED(struct semaphore *sem); //Initial value 0

  • void down(struct semaphore *sem); //Can sleep

  • int down_interruptible(struct semaphore *sem); //Can be interrupted

  • int down_trylock(struct semaphore *sem); //m non-blocking

  • void up(struct semaphore *sem);

SYSTEMV semaphore:

  • include

  • ##int semget(key_t key, int nsems, int oflag);

  • ##int semop(int semid, struct sembuf *opsptr, size_t nops);
  • int semctl(int semid , int semum, int cmd,...);
  • POSIX unnamed semaphore

    include
  • sem_t sem;
  • int sem_init(sem_t *sem, int pshared, unsigned int val); //If pshared is 0, it is shared between threads, pshared If it is 1, the parent and child processes share
  • int sem_wait(sem_t *sem); //Blocking
  • int sem_trywait(sem_t *sem); / /Non-blocking
  • ##int sem_post(sem_t *sem);
  • int sem_destroy(sem_t *sem);
  • If shared between processes, sem must be placed in the shared memory area (mmap, shm_open, shmget). Storage in the global variables, heap, and stack of the parent process is not acceptable
  • POSIX named semaphore

sem_t *sem_open(const char *name, int oflag, mode_t mode, int val);
  • int sem_wait( sem_t *sem);
  • int sem_trywait(sem_t *sem);
  • ##int sem_post(sem_t *sem);

  • int sem_close(sem_t *sem);

  • int sem_unlink(const char *name);

  • Each The position of open requires close and unlink, but only the last executed unlink takes effect

The above is the detailed content of Detailed explanation of various types of semaphores in Linux. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn