Multithreading in C ++
Zookeeper
1. Multithreading
Multithreading case:
# Include
# Include
# Include
# Include
Usingnamespacestd;
Voidrun (intnum)
{
Sleep (1000 );
Std: cout <"Hello tianchao" <num <
}
Voidmain ()
{
Thread * p [10];
For (inti = 0; I <10; I ++)
{
P [I] = newthread (run, I); // create a thread cyclically
// P [I]-> join (); // wait, equivalent to blocking
P [I]-> detach (); // execute freely from the current main thread in disorder. That is to say, the execution of each thread is random and is executed concurrently.
}
Cin. get ();
}
The running result is:
2. Thread case 2
# Include
# Include
# Include
# Include
Usingnamespacestd;
Voidhelloworld ()
{
Std: cout <"" <endl;
}
VoidhelloworldA ()
{
Std: cout <" A" <endl;
}
VoidhelloworldB ()
{
Std: cout <" B" <endl;
}
// The threads implemented in the following way are always sequential.
Voidmain ()
{
Std: threadt1 (helloworld); // sequential thread execution
Std: threadt2 (helloworldA );
Std: threadt3 (helloworldB );
Cin. get ();
}
3. thread locking and thread unlocking
# Include
# Include
# Include
# Include
# Include
Usingnamespacestd;
// Two threads access a variable in parallel
Intg_num = 20; // The identifier that cannot be found or found.
Mutexg_mutex;
VoidgoA (intnum)
{
// The variables you access, which cannot be accessed by others during your access,
// In this case, you can see that you have been executed more often.
G_mutex.lock ();
For (inti = 0; I <15; I ++)
{
Sleep (300 );
G_num = 10;
Std: cout <"Thread" <num <"" <
}
G_mutex.unlock ();
}
VoidgoB (intnum)
{
For (inti = 0; I <15; I ++)
{
Sleep (500 );
G_num = 11;
Std: cout <"Thread" <num <"" <
}
}
Voidmain ()
{
Threadt1 (goA, 1 );
Threadt2 (goB, 2 );
T1.join ();
T2.join ();
Std: cin. get ();
}
Running result:
4. Communication and lock between threads <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vcd4kcjxwprc4wp2juw.vcd4kcjxwiggfsawdupq = "left"> # include
# Include
# Include
# Include
Usingnamespacestd;
// Two threads access a variable in parallel
// The ID that is found or cannot be found
Intg_num = 20;
VoidgoA (intnum)
{
For (inti = 0; I <15; I ++)
{
Sleep (1000 );
If (I = 6)
{
G_num = 5;
}
If (g_num = 5)
{
Std: cout <"Thread" <num <"End \ n ";
Return;
}
Std: cout <"Thread" <num <"" <
}
}
VoidgoB (intnum)
{
For (inti = 0; I <150; I ++)
{
Sleep (1000 );
If (g_num = 5)
{
Std: cout <"Thread" <num <"End \ n ";
Return;
}
Std: cout <"Thread" <num <"" <
}
}
Voidmain ()
{
Threadt1 (goA, 1 );
Threadt2 (goB, 2 );
T1.join ();
T2.join ();
Std: cin. get ();
}