Search code examples
pthreadsglobal-variablesglobalmutexargv

Use Commands from argv to Initialize a Global Mutex


What I wish to do is to define a global mutex using data from argv. Not a problem, except that I also want this mutex to be global.

This isn't global::

int main (int argc, char **argv)
{
     int arg_1 = atoi(argv[1]);  
     pthread_mutex_t mutex[arg_1];
     return 0;
}

And this isn't possible:

pthread_mutex_t mutex[arg_1];

int main (int argc, char **argv) {
     int arg_1 = atoi(argv[1]);`
     return 0;
}

So what should I do to be able to have a mutex accessible in all of my functions that is defined by user input?


Solution

  • You can use dynamic allocation, just like you would for any other type. The only difference here is that dynamically allocated mutexes must be initialised with pthread_mutex_init():

    pthread_mutex_t *mutex;
    size_t n_mutex;
    
    int main (int argc, char **argv)
    {
        size_t i;
    
        if (argc < 2)
            return 1;
    
        n_mutex = atoi(argv[1]);
    
        if (n_mutex == 0)
            return 2;
    
        mutex = calloc(n_mutex, sizeof mutex[0]);
    
        if (!mutex)
            return 3;
    
        for (i = 0; i < n_mutex; i++) {
            if (pthread_mutex_init(&mutex[i], NULL))
                return 4;
        }
    
        /* global array mutex[] is initialised and can be used */
    
        return 0;
    }