I am using the pthread library to create two threads. I am using two queues to communicate the data between the two threads (producer-consumer) and hence want to have a mute
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 topthread_mutex_init()
with parameterattr
specified asNULL
, except that no error checks are performed.
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;
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.