dimanche 16 juillet 2017

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.

If any one of the thread is going to hijack the execution by not allowing other thread to be switched in between then how do i handle such a scenario with while/for loops in each thread but both threads needs to be continuously executed ? Where I want both the threads to keep switching their execution. Shall I lock and unlock inside the while loop, so that each iteration has mutex locked & unlocked ?

Aucun commentaire:

Enregistrer un commentaire