user2882307
user2882307

Reputation:

static mutex and multithreading

If I declare a mutex as static in a function and use that mutex to lock a certain variable. Is that mutex 'shared' between threads, e.g I can get away with using a little bit of cleaner code?

example of appending a string to a double pointer char type, I want to call something like this from multiple threads:

void func(char *msg) {
    static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
    static char **buffer;
    static unsigned int i=0;

    pthread_mutex_lock(&mtx);
    buffer = realloc(++i * sizeof(char *));
    buffer[i-1] = realloc(strlen(msg) + 1);
    strcpy(buffer[i-1], msg);
    pthread_mutex_unlock(&mtx);

    return;

}

Upvotes: 5

Views: 2861

Answers (1)

user4815162342
user4815162342

Reputation: 154996

Yes, a statically initialized mutex is shared between threads - otherwise it would not be very useful. PTHREAD_MUTEX_INITIALIZER is designed exactly for use cases like yours.

Note that you need to increment i after locking the mutex. As written before the edit, the code contained a data race (itself undefined behavior) and was open to a race condition if multiple threads executed it in parallel.

Upvotes: 6

Related Questions