Вопрос . Могу ли мне также заблокировать указатель на общий ресурс: < /p>
Код: Выделить всё
void foo (int * pi = nullptr)
{
//{..} some ops
static std::mutex mtx;
std::unique_lock lock(mtx); // lock mutex BEFORE ptr check
if(pi){
++(*pi); // dereference ptr's shared resource
}
lock.unlock();
//{...} some ops
}
void foo (int * pi = nullptr)
{
//{..} some ops
static std::mutex mtx;
if(pi){ // check if ptr is not null, is this thread-safe ?
std::unique_lock lock(mtx); // lock mutex ONLY for access shared resource itself,
// not for pointer that refers to it
++(*pi); // dereference ptr's shared resource
lock.unlock();
}
//{...} some ops
}
< /code>
Здесь какой -то глупый «синтетический» пример примера с общим ресурсом: < /p>
int main(){
int __i = 0;
std::thread t([&__i](){
for(;;){
foo(&__i);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
});
for(;;){
foo(&__i);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
//std::cout
Подробнее здесь: https://stackoverflow.com/questions/797 ... oncurrency
Мобильная версия