C pthread mutex: Expected expression before `{'

后端 未结 2 639
梦毁少年i
梦毁少年i 2021-01-04 08:24

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

相关标签:
2条回答
  • 2021-01-04 09:12

    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.

    0 讨论(0)
  • 2021-01-04 09:18
    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.

    0 讨论(0)
提交回复
热议问题