利用信号量和锁机制,可以实现线程互斥地访问共有资源或数据.实现代码如下: #ifndef CRITICAL_H_ #define CRITICAL_H_ #include <sys/ipc.h> #include <sys/sem.h> typedef int CRITICAL_SEC; union semun { int val; struct semid_ds *buf; unsigned short int *array; struct seminfo *__buf; }; class CCriticalSec { public: CCriticalSec() { m_pCriticalSec = semget (IPC_PRIVATE, 1, IPC_CREAT); //创建信号量 union semun argument; unsigned short values[1]; values[0] = 1; argument.array = values; semctl (m_pCriticalSec, 0, SETALL, argument); } ~CCriticalSec() { union semun ignored_argument; semctl (m_pCriticalSec, 1, IPC_RMID, ignored_argument); } unsigned short Lock() { struct sembuf operations[1]; /* Use the first (and only) semaphore. */ operations[0].sem_num = 0; /* Decrement by 1. */ operations[0].sem_op = -1; /* Permit undo ing. */ operations[0].sem_flg = SEM_UNDO; return semop (m_pCriticalSec, operations, 1); } unsigned short Unlock() { struct sembuf operations[1]; /* Use the first (and only) semaphore. */ operations[0].sem_num = 0; /* Increment by 1. */ operations[0].sem_op = 1; /* Permit undo ing. */ operations[0].sem_flg = SEM_UNDO; return semop (m_pCriticalSec, operations, 1); } private: CRITICAL_SEC m_pCriticalSec; }; #endif