pthread互斥锁,使用pthread_mutex_trylock()进行线程同步

时间:2014-05-25 04:10:19

标签: multithreading pthreads

我一直在努力获取一个键值哈希字典,我需要做的一件事是在加载因子达到阈值时重新进行,所以为了确保没有其他线程正在访问它我正在尝试把它归结为一个队列。

这是否会成功阻止多个线程同时读取/写入资源,或者是否存在我遗漏的内容。

谢谢!

typedef struct {
  pthread_mutex_t mutex;
  pthread_cond_t cond;
  pthread_rwlock_t rw_lock;
} thread_conch;

typedef struct {
  thread_conch d_lock;
  size_t elements;
  size_t hash_size;
  struct kv_record **bucket;
} dictionary;

void init_conch(thread_conch *t_lock)
{
  pthread_mutex_init(&t_lock->mutex, NULL);
  pthread_cond_init(&t_lock->cond, NULL);
  pthread_rwlock_init(&t_lock->rw_lock, NULL);
}

void destroy_conch(thread_conch *t_lock)
{
  pthread_mutex_destroy(&t_lock->mutex);
  pthread_cond_destroy(&t_lock->cond);
  pthread_rwlock_destroy(&t_lock->rw_lock);
}

void hold_conch(thread_conch *t_lock)
{
  pthread_rwlock_wrlock(&t_lock->rw_lock);
  while (pthread_mutex_trylock(&t_lock->mutex) != 0)
    ;
}

void read_conch(thread_conch *t_lock)
{
  while (pthread_rwlock_tryrdlock(&t_lock->rw_lock) != 0)
    pthread_cond_wait(&t_lock->cond, &t_lock->mutex);

}
void release_conch(thread_conch *t_lock)
{
  pthread_rwlock_unlock(&t_lock->rw_lock);
  pthread_mutex_unlock(&t_lock->mutex);
  pthread_cond_broadcast(&t_lock->cond);
}

0 个答案:

没有答案