C pthread mutex: Expected expression before `{' C pthread mutex: Expected expression before `{' c c

C pthread mutex: Expected expression before `{'


  1. You can't use PTHREAD_MUTEX_INITIALIZER like that - it has to be used as an initializer, not in a regular assignment expression. You have two choices to fix it - either call pthread_mutex_init(), or add a typecast to use PTHREAD_MUTEX_INITIALIZER as a compound literal. Your choice of:

    pthread_mutex_init(&q->mutex, NULL);

    or:

    q->mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
  2. Your linker error problem is due to this command line:

    gcc simple-tun.c simple-tun -lpthread

    You're missing a -o, so you're trying to link the program with itself. That's bad news. What you probably want is:

    gcc simple-tun.c -o simple-tun -lpthread

    And really, you should add some warning flags in there, too.


PTHREAD_MUTEX_INITIALIZER is exactly that, an initializer to use in declarations:

pthread_mutex_t foo = PTHREAD_MUTEX_INITIALIZER;

if you have a pthread_mutex_t that was created elsewhere - such as by malloc - initialize it with pthread_mutex_init:

pthread_mutex_init(&q->mutex, NULL);

from the SUSV2 documentation for pthread_mutex_init:

In cases where default mutex attributes are appropriate, the macro PTHREAD_MUTEX_INITIALIZER can be used to initialise mutexes that are statically allocated. The effect is equivalent to dynamic initialisation by a call to pthread_mutex_init() with parameter attr specified as NULL, except that no error checks are performed.