【发布时间】:2012-08-10 18:41:54
【问题描述】:
我想通过使用互斥锁访问数组的每个元素来使结构数组中的每个元素都成为线程安全的。
这是我的结构:
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);
}
【问题讨论】:
-
你能在你使用互斥锁的地方显示一些代码吗?
-
为什么你有
mutex作为一个指针,而不是直接作为一个pthread_mutex_t?分配*mutex似乎使您的生活复杂化。 -
前提是有缺陷的,无论它看起来如何。互斥体阻塞代码,它不锁定数据。
-
我已经发布了一些相关代码。
-
在调试器中,或者通过打印,是否验证了这两个项目是同一个项目?
标签: c linux multithreading structure mutex