- 论坛徽章:
- 0
|
大家幫忙看一下,這樣的用mutex模擬semaphore, 有沒問題呢?
- typedef struct
- {
- mutex_t lock;
- mutex_t wait;
- int count;
- } sem_t;
- void sem_init( sem_t &sem, int count )
- {
- sem->count = count;
- mutex_init( &sem->lock );
- mutex_init( &sem->wait );
- mutex_lock( &sem->wait );
- }
- void sem_wait( sem_t &sem )
- {
- int count;
- mutex_lock( &sem->lock );
- count = --sem->count;
- mutex_lock( &sem->unlock );
- if ( count < 0 )
- mutex_lock( &sem->wait );
- }
- void sem_post( sem_t &sem )
- {
- int count;
- mutex_lock( &sem->lock );
- count = ++sem->count;
- mutex_lock( &sem->unlock );
- if ( count <= 0 )
- mutex_unlock( &sem->wait );
- }
- void sem_destory( sem_t &sem )
- {
- mutex_destroy( &sem->wait );
- mutex_destroy( &sem->lock );
- }
复制代码 |
|