cpointerspthreadsmutexconst-pointer

const pointer to struct containing a mutex


I have something like this:

typedef struct
{
    pthread_mutex_t mtx;
    /* Other stuff */
} some_struct_t;

void some_func (some_struct_t *s)
{
    pthread_mutex_lock (&s->mtx);
    /* Some stuff */
    pthread_mutex_unlock (&s->mtx);
}

some_func does not modify s, and I would like to change the signature to

void some_func (const some_struct_t *s);

but the calls to pthreads functions won't allow me to do that without warnings.

Is there any common idiom I could use to express that the some_struct_t will be logically constant inside the function?

Any way to use some_func from inside another function which has a const some_struct_t *s without doing a cast?


Solution

  • some_funcmodifies the mtx member, so it cannot be const.

    But you can make mtx a pointer. You then still change the mutex, but that will no longer be covered by the const.

    typedef struct
    {
        pthread_mutex_t *mtx;
        /* Other stuff */
    } some_struct_t;
    
    void some_func(const some_struct_t *s)
    {
        pthread_mutex_lock(s->mtx);
        /* Some stuff */
        pthread_mutex_unlock(s->mtx);
    }
    
    int main()
    {
        pthread_mutex_t mtx = MUTEX_INITIALIZER;
        some_struct s = {
            .mtx = &mtx;
        };
        some_func(&s);
    }
    

    Now some_func no longer modifies s, but initializing a some_struct variable (and cleaning it up) has become a little bit more involved.