c - 结构数组中每个元素的互斥锁

标签 c linux multithreading structure mutex

我想通过使用互斥锁来访问数组的每个元素,使结构数组中的每个元素都是线程安全的。

这是我的结构:

typedef struct {
  void      *value;
  void      *key;
  uint32_t  value_length;
  uint32_t  key_length;
  uint64_t  access_count;
  void      *next;
  pthread_mutex_t *mutex;
} lruc_item;

我有一个这种结构的数组,并且想使用互斥锁来使结构元素线程安全。

我尝试在函数中的一个数组元素上使用锁,然后故意没有解锁它,只是为了确保我的锁工作正常,但奇怪的是没有死锁和第二个函数访问相同的数组元素能够访问它。

有人可以指导我如何使用互斥锁锁定结构数组中的每个元素(以便使结构线程的每个元素安全)。

示例代码来解释我的观点:

/** FUNCTION THAT CREATES ELEMENTS OF THE STRUCTURE **/

lruc_item *create_item(lruc *cache) {
  lruc_item *item = NULL;

item = (lruc_item *) calloc(sizeof(lruc_item), 1);

item->mutex = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
  if(pthread_mutex_init(item->mutex, NULL)) {
    perror("LRU Cache unable to initialise mutex for page");
    return NULL;
     }

  }

 return item;
}


set()
{
item = create_item(cache);

  pthread_mutex_lock(item->mutex);
    item->value = value;
    item->key = key;
    item->value_length = value_length;
    item->key_length = key_length;
    item->access_count = ++cache->access_count;

  pthread_mutex_unlock(item->mutex);     /** (LINE P) tried commenting out this to check  proper working of mutex(deadlock expected if the same "item" is accessed in another function)  **/


}

get(lruc_item *item)
{

  pthread_mutex_lock(item->mutex);   /** deadlock doesn't occur when "LINE P" is commented out**/ 
    *value = item->value;
    item->access_count = ++cache->access_count;
  pthread_mutex_unlock(item->mutex);

}

最佳答案

重要的是要注意,互斥量只会锁定来自其他线程的代码。 如果您尝试在同一线程中使用相同的互斥体执行 WaitForMultipleObjects,它不会阻塞。我假设是 Windows,因为你没有详细说明。

但是,如果您提供更多详细信息,也许我们可以查明问题的真正所在。

现在,再次假设是 Windows,如果您想对单个元素进行“线程安全”访问,您可能需要考虑 InterlockedExchange-函数类而不是互斥量。例如:

InterlockExchange(&s.value_length, newValue);

InterlockedExchange64(&s.access_count, new64Value);

InterlockedExchangePointer(&s.value, newPointer);

如果您想做的是确保对结构的多个元素访问(作为事务)是线程安全的,那么互斥锁可以为您做到这一点。互斥量在跨进程边界时很有用。如果您只处理单个进程,那么关键部分可能是个更好的主意。

关于c - 结构数组中每个元素的互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11907445/

相关文章:

python - 无法让 Python Shutil.copytree 忽略模式正常工作

Java - 线程崩溃后应用程序无法正常工作

java - 这是没有 volatile 和同步开销的更好版本的 Double Check Locking

c - 堆排序程序不返回结果

c++ - 无效使用不完整类型 'PGconn {aka struct pg_conn}'

c - Linux pthread_suspend

linux - awk 命令,打印在 csv 文件中只出现一次的行

c - fscanf 读入双数组奇怪值

c - 如何在内核 C 中将 size_t 转换为 char*?

c++ - 执行类的成员函数