tonythestark
tonythestark

Reputation: 543

Initialise mutex globally in C

I have some code where two 2 threads modify the value of the same variable but with two different functions. So I decided to use a common mutex. That for: I initialised it globally :

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>


#define perror_pthread(ret, msg) \
        do { errno = ret; perror(msg); } while (0)



pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;      /*define a mutex-object */ 
pthread_mutex_init(&mutex,NULL);  /*initialise this mutex object with default values */

I get an error message :

error: expected declaration specifiers or ‘...’ before ‘&’ token
 pthread_mutex_init(&mutex,NULL);  /*initialise this mutex object with default values */
                    ^

I don't know if that's a good practice, but I feel like both functions should have the same mutex in order to be informed when there is lock

Upvotes: 0

Views: 1106

Answers (1)

tstanisl
tstanisl

Reputation: 14107

pthread_mutex_init is a function and C forbids expressions (i.e. function calls) at the file scope.

Either use static initializer or put pthread_mutex_init(...) into beginning of main().

Upvotes: 2

Related Questions