Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

multithreading - C++ Initialize struct with mutex field

I'm trying to figure out how to initialize a struct with a mutex field, since the mutex type is not copyable or movable in C++.

I have the struct:

typedef struct sample {
  int field1;
  std::mutex mtx;
} sample_t;

I'm trying to initialize it in the following way, but I keep getting error: use of deleted function. I'm not super familiar with C++ and would love some help!

sample_t* new_sample;
std::mutex a_mtx;
// new_sample->mtx = std::move(a_mtx); (I tried this too)
new_sample->mtx = a_mtx;
new_sample->mtx.lock();
new_sample->field1 = 2;
new_sample->mtx.unlock();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Mutex is not copyable and not moveable. But you don't need either of these operatons, you only need to create sample_t object - std::mutex inside will be initilized by the compiler.

sample_t new_sample;

new_sample.mtx.lock();
new_sample.field1 = 2;
new_sample.mtx.unlock();

Or, if you really need a pointer for some reason :

// sample_t* new_sample = new sample_t;
// you should prefer smart pointers over raw pointers
std::unique_ptr<sample_t> new_sample = std::make_unique<sample_t>();

new_sample->mtx.lock();
new_sample->field1 = 2;
new_sample->mtx.unlock();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...