简体   繁体   English

如何在结构中初始化互斥锁?

[英]How to Initialize a Mutex Inside a Struct?

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:目前,我有一个 C++ 结构如下:

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?我见过有人为struct对象创建了一个构造函数,并在构造函数中初始化了互斥体,但我们为什么需要它呢? Also, is there a way to do it without a constructor?另外,有没有办法在没有构造函数的情况下做到这一点?

Thank you very much.非常感谢。

You can't perform non-declarative statements inside of a struct declaration.您不能在struct声明中执行非声明性语句。 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:话虽如此,如果您使用的是 C++11 或更高版本,则应使用std::mutex (和std::condition_variable ):

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.并考虑使用std::thread而不是 pthreads。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM