Do mutex in C ++ need to be bound to some object or variable?

I'm a little new to streaming, and I'm trying to understand how it works in C ++ 11. A professor in my class gave us this sample code to demonstrate the use of the mutex:

#include <list> 
#include <mutex> 
#include <algorithm>

std::list<int> some_list; // A data structure accessed by multiple threads
std::mutex some_mutex; // This lock will prevent concurrent access to the shared data structure

void
add_to_list(int new_value) {
    std::lock_guard<std::mutex> guard(some_mutex); // Since I am going to access the shared data struct, acquire the lock
    some_list.push_back(new_value); // Now it is safe to use some_list. RAII automatically releases lock at end of function }
}

bool
list_contains(int value_to_find) {
    std::lock_guard<std::mutex> guard(some_mutex); // Must get lock every time I access some_list return
    std::find (some_list.begin(),some_list.end(),value_to_find) != some_list.end();
}

I think the code is somewhat clear, but I had some specific questions.

  • Is there any need to specifically associate a mutex with a list?
  • And if not, does this mean that at any time when the mutex is used, all threads stop until the mutex is destroyed? Or is it just a subset of threads; perhaps threads in some thread or otherwise connected to each other?
  • , , ? ..
  • , ? RAII? RAII ?
+5
4
  • , - , . , , , , / .

  • , , , / , ( ), . , , .

  • , , , / , , , , / . , .

  • : "", "" " ". RAII / .

+5

?

, , , , . () , , , , . , ( , ).

, , , , , ? ; , - ?

, , , , , , . , , ( "" ) , .

, , ? ..

, . ( ), , , .

, ? RAII? RAII ?

- , () , , , ( , , ).

RAII, . , ( - , ..), .

+3

?

. .

, , , , , ? ; , - ?

mutex = . , , , . , , , .

, , ? ..

. , , . . . add_to_list mutex (some_mutex) some_list.push_back().

, ? RAII?

++ lock_guard RAII . , , ( ), .

+2

?

, . , . some_list.push_back() std::find , , , .

, , , , , ? ; , - ?

- , , , , ( lock_guard, ).

, , ? ..

, , , , .

, ? RAII? RAII ?

, - , - , ++ . : lock, try_lock unlock, . , RAII, std::lock_guard.

+2

All Articles