利用POSIX互斥鎖、條件變量,和內存映射文件,實現的信號量機制,用於進程間的同步。
- /* sem.h */
- struct semaphore
- {
- pthread_mutex_t lock;
- pthread_cond_t nonzero;
- unsigned count;
- };
- typedef struct semaphore semaphore_t;
-
-
- semaphore_t* semaphore_create(char *semaphore_name);
- semaphore_t* semaphore_open(char *semaphore_name);
- void semaphore_post(semaphore_t *semap);
- void semaphore_wait(semaphore_t *semap);
- void semaphore_close(semaphore_t *semap);
-
-
- /* sem.c */
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/mman.h>
- #include <fcntl.h>
- #include <pthread.h>
- #include "sem.h"
-
-
- semaphore_t* semaphore_create(char *semaphore_name)
- {
- int fd = open(semaphore_name, O_RDWR | O_CREAT | O_EXCL, 0666);
- if (fd < 0) return (NULL);
- (void) ftruncate(fd, sizeof(semaphore_t));
-
- pthread_mutexattr_t psharedm;
- pthread_condattr_t psharedc;
- (void) pthread_mutexattr_init(&psharedm);
- (void) pthread_mutexattr_setpshared(&psharedm, PTHREAD_PROCESS_SHARED);
- (void) pthread_condattr_init(&psharedc);
- (void) pthread_condattr_setpshared(&psharedc, PTHREAD_PROCESS_SHARED);
- semaphore_t* semap = (semaphore_t *) mmap(NULL,
- sizeof(semaphore_t),
- PROT_READ | PROT_WRITE,
- MAP_SHARED,
- fd,
- 0);
- close (fd);
- (void) pthread_mutex_init(&semap->lock, &psharedm);
- (void) pthread_cond_init(&semap->nonzero, &psharedc);
-
- // 我覺得應該給個大於零的初值
- semap->count = 0;
- return (semap);
- }
-
-
- semaphore_t* semaphore_open(char *semaphore_name)
- {
- int fd = open(semaphore_name, O_RDWR, 0666);
- if (fd < 0) return (NULL);
-
- semaphore_t* semap = (semaphore_t *) mmap(NULL,
- sizeof(semaphore_t),
- PROT_READ | PROT_WRITE,
- MAP_SHARED,
- fd,
- 0);
- close (fd);
- return (semap);
- }
-
-
- void semaphore_post(semaphore_t *semap)
- {
- pthread_mutex_lock(&semap->lock);
- // 計數為零,說明可能有線程已經阻塞在該條件變量上
- if (semap->count == 0)
- {
- pthread_cond_signal(&semapx->nonzero);
- }
- semap->count++;
- pthread_mutex_unlock(&semap->lock);
- }
-
-
- void semaphore_wait(semaphore_t *semap)
- {
- pthread_mutex_lock(&semap->lock);
- // 計數為零,說明已無資源,等待
- while (semap->count == 0)
- {
- pthread_cond_wait(&semap->nonzero, &semap->lock);
- }
- semap->count--;
- pthread_mutex_unlock(&semap->lock);
- }
-
-
- void semaphore_close(semaphore_t *semap)
- {
- munmap((void *) semap, sizeof(semaphore_t));
- }