Home > Mobile >  How to Initialize a Mutex Inside a Struct?
How to Initialize a Mutex Inside a Struct?

Time:07-14

I'm kind of new to multithreading, and this is a small piece of a very large homework for my operating systems class. Currently, I have a C struct as follows:

struct arguments {
    std::string string1;
    std::string string2;
    pthread_mutex_t bsem;
    pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
    pthread_mutex_init(&bsem, NULL);
    int turn_index = 0; // To identify which thread's turn it is.
};

The line containing:

pthread_mutex_init(&bsem, NULL);

Is giving me errors, namely the two:

  • expected an identifier before &
  • expected an identifer before _null

What is a quick resolve to this? I've seen someone make a constructor for the struct object and initalized the mutex in the constructor, but why do we need that? Also, is there a way to do it without a constructor?

Thank you very much.

CodePudding user response:

You can't perform non-declarative statements inside of a struct declaration. What you can do is add a constructor (and destructor, in this case) that performs the extra statements you need, eg:

struct arguments {
    std::string string1;
    std::string string2;
    pthread_mutex_t bsem;
    pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
    int turn_index = 0; // To identify which thread's turn it is.

    arguments() {
        pthread_mutex_init(&bsem, NULL);
    }

    ~arguments() {
        pthread_mutex_destroy(&bsem);
    }
};

That being said, if you are using C 11 or later, you should use std::mutex (and std::condition_variable) instead:

struct arguments {
    std::string string1;
    std::string string2;
    std::mutex bsem;
    std::condition_variable wait;
    int turn_index = 0; // To identify which thread's turn it is.
};

And consider using std::thread instead of pthreads.

  • Related