锁定状态期间互斥锁指针可以改变吗?
can mutex pointer change during lock state?
所以我有一个使用数据缓冲区的 "producer & consumer" 程序,现在我想让缓冲区成为流动的数据流。
我为数据缓冲区制作了一个类似于链表的数据结构。
有一个复杂的对象,它存储一个指向链表头部的指针和一个指向链表尾部的指针。
也许术语不正确,但我指的是 "next" 的位置。
(随时纠正我的问题)
我需要将新项目添加到列表的头部,但是,由于我使用的是线程,因此我需要先锁定缓冲区对象。所以我的问题是:更改指向它的指针后可以解锁互斥量吗?
在此代码中,我尝试保留对 bf_head
的引用,以便稍后解锁它:
void *producer(void *args)
{
/* some code */
pthread_mutex_lock(&co->bf_head->lock);
bf_tmp = co->bf_head;
co->bf_head->next = bf_new;
co->bf_head = bf_new;
pthread_mutex_unlock(&bf_tmp->lock);
/* some code */
}
其中:
struct complex_obj *co = args;
struct buffer *bf_new;
struct buffer *bf_tmp;
和:
typedef struct complex_obj
{
struct file_acess *file_acess;
struct buffer *bf_head;
struct buffer *bf_tail;
struct stat *stat;
}s_complex_obj;
typedef struct buffer
{
char *line;
struct buffer *next; //for liknked list
pthread_mutex_t lock;
pthread_cond_t cons_cond; //not used yet
int full; //-1 at the end
}s_buffer;
是的,你可以做到,这完全没问题。
你不改变互斥锁本身,而是指向它的变量 the 指向它,因此在访问指向的互斥锁时,没有区别。 (在这里,你甚至不持有指向互斥锁的指针,而是指向你 bf_head 成员)
就是说,我不确定您的代码是否完全没有竞争,但那是另一回事了:)
所以我有一个使用数据缓冲区的 "producer & consumer" 程序,现在我想让缓冲区成为流动的数据流。
我为数据缓冲区制作了一个类似于链表的数据结构。 有一个复杂的对象,它存储一个指向链表头部的指针和一个指向链表尾部的指针。
也许术语不正确,但我指的是 "next" 的位置。 (随时纠正我的问题)
我需要将新项目添加到列表的头部,但是,由于我使用的是线程,因此我需要先锁定缓冲区对象。所以我的问题是:更改指向它的指针后可以解锁互斥量吗?
在此代码中,我尝试保留对 bf_head
的引用,以便稍后解锁它:
void *producer(void *args)
{
/* some code */
pthread_mutex_lock(&co->bf_head->lock);
bf_tmp = co->bf_head;
co->bf_head->next = bf_new;
co->bf_head = bf_new;
pthread_mutex_unlock(&bf_tmp->lock);
/* some code */
}
其中:
struct complex_obj *co = args;
struct buffer *bf_new;
struct buffer *bf_tmp;
和:
typedef struct complex_obj
{
struct file_acess *file_acess;
struct buffer *bf_head;
struct buffer *bf_tail;
struct stat *stat;
}s_complex_obj;
typedef struct buffer
{
char *line;
struct buffer *next; //for liknked list
pthread_mutex_t lock;
pthread_cond_t cons_cond; //not used yet
int full; //-1 at the end
}s_buffer;
是的,你可以做到,这完全没问题。
你不改变互斥锁本身,而是指向它的变量 the 指向它,因此在访问指向的互斥锁时,没有区别。 (在这里,你甚至不持有指向互斥锁的指针,而是指向你 bf_head 成员)
就是说,我不确定您的代码是否完全没有竞争,但那是另一回事了:)