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.
, - , . , , , , / .
, , , / , ( ), . , , .
, , , / , , , , / . , .
: "", "" " ". RAII / .
?
, , , , . () , , , , . , ( , ).
, , , , , ? ; , - ?
, , , , , , . , , ( "" ) , .
, , ? ..
, . ( ), , , .
, ? RAII? RAII ?
- , () , , , ( , , ).
RAII, . , ( - , ..), .
. .
mutex = . , , , . , , , .
. , , . . . add_to_list mutex (some_mutex) some_list.push_back().
add_to_list
some_mutex
some_list.push_back()
, ? RAII?
++ lock_guard RAII . , , ( ), .
, . , . some_list.push_back() std::find , , , .
std::find
- , , , , ( lock_guard, ).
lock_guard
, , , , .
, - , - , ++ . : lock, try_lock unlock, . , RAII, std::lock_guard.
lock
try_lock
unlock
std::lock_guard