【发布时间】:2018-10-28 16:30:29
【问题描述】:
所以我有一个使用数据缓冲区的“生产者和消费者”程序,现在我想让缓冲区成为流动的数据流。
我为数据缓冲区创建了一个类似于链表的数据结构。 有一个复杂的对象,它存储了一个指向链表头的指针和一个指向链表尾的指针。
也许这些术语不正确,但我的意思是“下一个”在哪里。 (请随时纠正我的问题)
我需要将新项目添加到列表的头部,但是,因为我使用的是线程,所以我需要先锁定缓冲区对象。所以我的问题是:可以在更改指针后解锁互斥锁吗?
在这段代码中,我尝试保留对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;
【问题讨论】: