Example 1:
STD: : mutex lock 1;
Static int I=0;
Thread 1:
{
STD: : lock_guard & lt; STD: : mutex> Lk lock (1);
I=I + 1;
}
Thread 2:
{
STD: : lock_guard & lt; STD: : mutex> Lk lock (1);
I=I + 1;
}
Example 2:
STD: : mutex lock 1;
STD: : mutex locking 2;
Static int I=0;
Thread 1:
{
STD: : lock_guard & lt; STD: : mutex> Lk lock (1);
I=I + 1;
}
Thread 2:
{
STD: : lock_guard & lt; STD: : mutex> Lk lock (2);//this is lock 2
I=I + 1;
}
CodePudding user response:
I.e., the two threads of example 1 to use the same lock, 1 example 2 two threads with different lock lock 1 and 2, which of these two kinds of usage is for? Or for both, but is there a difference? Please the teacher guidance, thank you very much!CodePudding user response:
Example 1 is right,Example 2 is equal to didn't lock,
CodePudding user response:
Examples of course there's a difference, one equivalent to have a room now, there is a girl in the room.. The forehead not.. A I, then only one room door, the door have a lock, the outside people want to go in to see the girl... Look, I can only get the key to get in, that is to say, only after someone else read it out to obtain a key to get in to see the second example is equivalent to the room has two doors, two doors each have a key, so there are at least two people are can simultaneously by two door into the girl.. See I, they will fight...CodePudding user response:
Well, this question is pretty basic, hahaWhy you know the first multithreaded lock, lock is to lock a global resource, a thread to access the resources, another thread must wait
You example 2 is equivalent to string two locks up to open any lock can access the I, so it is no good
CodePudding user response:
Take care of me, look at my blog