C++11 Multithreading

Source: Internet
Author: User

C++11 began to support multi-threaded programming, before multithreaded programming requires system support, in different systems to create a thread requires a different API such as Pthread_create (), CreateThread (), beginthread (), etc., use is more complex, c+ +11 provides new header files <thread>, <mutex>, <atomic>, <future> and more to support multithreading.

Using C++11 to open a thread is relatively straightforward, so here's a simple example:

#include <thread>

#include <iostream>

void Hello ()

{

Std::cout << "Hello from thread" << Std::endl;

}

int main ()

{

Std::thread T1 (hello);

T1.join ();

std::cout<< "Main Thread" <<std::endl;

return 0;

}

Operation Result:

Description, through the thread class directly declare a thread T1, the parameter is the address of the callback function executed by this thread, block the main thread through the Jion () method until the end of the T1 thread execution.

C++11 supports lambda expressions, so a new thread's callback function can also be in the form of a lambda expression, but note that if you use a lambda expression to avoid referencing, you should use value passing to access the data and use references in multiple threads to cause confusion. The following example is slightly more complex, creating multiple sub-threads and using the get_id () method to get the ID of the current thread.

#include <thread>

#include <iostream>

#include <vector>

int main ()

{

Std::vector<std::thread> threads;

for (int i = 0; i < 5; ++i) {

Threads.push_back (Std::thread ([] () {

Std::cout << "Hello from Lamda thread" << std::this_thread::get_id () << Std::endl;

}));

}

for (auto& thread:threads) {

Thread.Join ();

}

std::cout<< "Main Thread" << "\ T" <<std::this_thread::get_id () <<std::endl;

return 0;

}

Operation Result:

In the code above, the vector is used to hold each thread, and the callback function of the thread is generated by the lambda expression, paying attention to how the subsequent join is used.

You can use Sleep_for to make the thread sleep for a certain amount of time:

#include <thread>

#include <iostream>

#include <mutex>

using namespace Std;

int main ()

{

Std::mutex m;

Thread T1 ([&m] ()

{

Std::this_thread::sleep_for (Chrono::seconds (10));

for (int i=0;i<10;i++)

{

M.lock ();

cout << "in T1 ThreadID:" << std::this_thread::get_id () << ":" << i << Endl;

M.unlock ();

}

} );

Thread T2 ([&m] ()

{

Std::this_thread::sleep_for (Chrono::seconds (1));

for (int i=0;i<10;i++)

{

M.lock ();

cout << "in T2 ThreadID:" << std::this_thread::get_id () << ":" << i << Endl;

M.unlock ();

}

} );

T1.join ();

T2.join ();

cout<< "Main Thread" <<endl;

return 0;

}

Operation Result:

As you can see, because the thread T1 sleep for a long time, T2 executes first.

There are several types of delay:nanoseconds, microseconds, milliseconds, seconds, minutes, and hours.

Be careful when you work with shared data in a multithreaded program, and you may get unexpected results due to the chaotic execution of threads. See the following procedure:

#include <thread>

#include <iostream>

#include <vector>

#include <mutex>

struct Counter {

Std::mutex Mutex;

int value;

Counter (): value (0) {}

void Increment () {

Mutex.lock (); "1" means no lock is used

++value;

Mutex.unlock (); "1"

}

void Decrement () {

Mutex.lock ();

--value;

Mutex.unlock ();

}

};

int main () {

Counter Counter;

Std::vector<std::thread> threads;

for (int i = 0; i < 5; ++i) {

Threads.push_back (Std::thread ([&] () {

for (int i = 0; i < 10000; ++i) {

Counter.increment ();

}

}));

}

for (auto& thread:threads) {

Thread.Join ();

}

Std::cout << counter.value << Std::endl;

return 0;

}

Operation Result:

"1"

Run Result: (lock used)

Description: Since the creation thread uses a lambda expression and accesses the counter variable using a reference, when no lock is used to protect it (case "1"), The results may not be as expected 5000 (the program means that each thread makes the value in counter 1000, 5 threads should be 5000 at the end of the run), and when no lock is used, the self-added operation may be interrupted by other threads, so the result may be less than 5000.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.