c++0x Overview: Multithreading (1)

Source: Internet
Author: User

The + + 0x standard will increase support for multithreading. All future compilers must follow the rules of multithreading in the new standard, which will bring great convenience to porting programs on different platforms.

Let's take a look at the Std::thread class, which is responsible for managing the thread's execution process.

Start thread

We create an instance of the Std::thread class to start a new thread, using a thread function as a constructor parameter. Such as

void do_work();
std::thread t(do_work);

The Std::thread class also accepts a function object as an argument.

class do_work
{
public:
void operator()();
};

do_work dw;
std::thread t(dw);

Notice that this is just a copy of the object that was sent in. If you want to pass the object itself (you should make sure that it is not destroyed before the thread ends), you can use Std::ref.

do_work dw;
std::thread t(std::ref(dw));

Many API creation threads allow you to pass an argument to a thread, such as long or void*. Std::thread also supports parameters, and can be any number of parameters of any type.

void do_more_work(int i,std::string s,std::vector<double> v);
std::thread
t(do_more_work,42,"hello",std::vector<double>(23,3.141));

You can also use Std::ref to pass the reference.

void foo(std::string&);
std::string s;
std::thread t(foo,std::ref(s));

Knowing how to start a thread, how do we wait for the thread to end? The new standard has a term called joining to work with threads, and we use member functions to join ()

void do_work();
std::thread t(do_work);
t.join();

If you don't want to joining your thread, you can destroy the thread object or call Detach ().

void do_work();
std::thread t(do_work);
t.detach();

Starting the thread is as simple as that. Next I'll explain how to share data between threads.

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.