Static Mutex and Multithreading

If I declare a mutex as static in a function and use this mutex to lock a specific variable. Is this mutex “shared” between threads, for example, can I get away using a bit of clean code?

an example of adding a string to a double pointer char type, I want to call something like this from several 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;

}
+4
source share
1 answer

Yes, a statically initialized mutex is split between threads, otherwise it would not be very useful. PTHREAD_MUTEX_INITIALIZERDesigned specifically for occasions like yours.

, i . , , .

+6

Source: https://habr.com/ru/post/1546691/


All Articles