C++11 Multithreading Std::thread Calling a method of a function in a class

Source: Internet
Author: User

When we are using thread to create a thread, we want to separate the threads, run a function, we just use the main thread, Std::thread (function name, parameter) can be
(If you don't understand, see: "Simple use of c++11 multithreaded Std::thread")

However, sometimes we want to open a thread and run a function inside a class.

For example: We have a class love with a member function shit (int)

What if we want to open a single thread and run the shit function?

The simple code is as follows:

#include"stdafx.h"#include<chrono>//Std::chrono::seconds#include <iostream>//Std::cout#include <thread>//Std::thread, Std::this_thread::sleep_forclasslove{ Public: Love (); ~Love (); voidShit (intding);}; Love::~Love () {}voidLove::shit (intDing) {Std::cout<< Ding <<"hahaha"<<Std::endl;}/** = = FUNCTION =========================================================* name:main* description:progra M entry routine.* ========================================================================*/intMainintargcConst Char*argv[]) {Love ABC;Std::thread TT (&love::shit,5); Tt.join ();return;} /*----------End of function main----------*/

We found a full compilation, but Ah!! There's Wood there!

Let's take a look at the main program, we'll set a Love class object abc

Then use

Std::thread TT (&love::shit,5

Want to thread, call the Love class inside the shit function, pass the parameter 5.

But the compilation does not pass.

Because the function inside the class, there is no object, how can it be called? So compile error ...

Therefore, we use

Std::thread TT (&love::shit,abc,5

We pass the object in, so the compilation is passed ...

PS: Pass "Object" in ... Oh, my God! What a lunatic! The object went in, I have to find the object again ah ...

C++11 Multithreading Std::thread Calling a method of a function in a class

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.