multithreading – Switching of execution between 2 threads in C++, if threads involve a loop between mutex lock & unlock

بدون دیدگاه


I’ve a vector of strings which is a shared resourse.

std::vector<std::string> vecstr;

Have 2 threads which run in parallel:

Thread1: To insert strings to shared resourse.

Thread2: To calculate the size of the shared resourse.

std::mutex mt;

void f1()
{
   mt.lock();
    while(some_condition())
   {
        std::string str = getStringFromSomewhere();
          vecstr.push_back(str);

   }

    mt.unlock();
}

size_t f2()
{
    mt.lock();
    while(string_sending_hasEnded())
    {
        size_t size = vecstr.size();
    }
    mt.unlock();
}

int main()
{
std::thread t1(f1);
std::thread t2(f2);
t1.join();
t2.join();

}

My question is : if the t1 thread keeps the vecstr shared resource mutex locked for the entire while loop duration how will the t2 get hold of the shared resource vecstr to calculate it’s size ?
Does the execution keep switching between the 2 threads or it depends on who gets hold of mutex 1st. So if T1 got hold of mutex then it will release it only after while loop ends ? Is this true ? Or the execution keeps switching between the 2 threads.



لینک منبع

  • نویسنده
    A-brand
  • تعداد بازدید
    15 views
0دیدگاه فرستاده شده است.
شما هم دیدگاه خود را بنویسید