Javier Fuentes
Javier Fuentes

Reputation: 43

can mutex pointer change during lock state?

So I have a "producer & consumer" program using a buffer of data, and now I want to make the buffer a flowing stream of data.

I made a linked-list like data structure for a buffer of data. There is a complex object which stores a pointer to the head, and a pointer to the tail of the linked-list.

Maybe the terms are not correct, but by the head I mean where the "next"one goes. (feel free to correct my question)

I need to add new items to the head of the list, but, since I'm using threads, I need to lock the buffer object firs. so my question is: is it okay to unlock a mutex after changing the pointer to it?

In this code I try to keep a reference to the bf_head so I can unlock it later:

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 */
}

where:

struct complex_obj *co = args;
struct buffer *bf_new;
struct buffer *bf_tmp;

and:

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;

Upvotes: 0

Views: 38

Answers (1)

OznOg
OznOg

Reputation: 4722

yes you can do that, this is perfectly ok.

you don't change the mutex itself, but the variable the points to it, thus when accessing the pointed mutex, there is no difference. (and here, you don't even hold the pointer to the mutex, but to you bf_head member)

That said, I'm not sure your code is completely race-free, but that's another story :)

Upvotes: 1

Related Questions