EnDelt64
EnDelt64

Reputation: 1360

Why is it impossible to pass mutex to function through Call-by-Value?

Full source code

If I pass mutex object to worker() without reference, it causes compile error.

void worker(int& p_counter, std::mutex p_mutex) {
    ...
}

=============================================================================

workers.push_back(std::thread(worker, std::ref(counter), mutex));

But if I pass it with reference, it is compiled well.

void worker(int& p_counter, std::mutex& p_mutex) {
    ...
}

=============================================================================

workers.push_back(std::thread(worker, std::ref(counter), std::ref(mutex)));

Why is mutex implemented to be passed to functions using references?

Upvotes: 0

Views: 484

Answers (2)

andresantacruz
andresantacruz

Reputation: 1724

If I pass mutex object to worker() without reference, it causes compile error

That's because std::mutex is a non-copyable class.

Why is mutex implemented to be passed to functions using references?

There is no reason to pass an object of std::mutex by value (and therefore copying it) as a mutex should be used for mutual exclusion to prevent race conditions (a function that receives it should be able to refer to the same mutex object as the one passed by the caller).

Upvotes: 4

Tony Tannous
Tony Tannous

Reputation: 14866

Because it makes no sense and doesn't serve the purpose of a mutex.

Lets say you could send a mutex by value (i.e. mutex had a copy constructor). A copy is passed and mutex is locked... its the copy that is locked. There's no guarantee that you are preventing race conditions. Thus, copy constructor is not present and it can't be send by value.

Upvotes: 3

Related Questions