std::thread calling method of class
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
Call a method of class inside a thread in C++
To compliment the answer of @Pete, you can bind the member function and feed your thread just like a normal function which accepts the object as its argument.
Airplaine* av1 = new Airplaine;
std::function<void(Airplaine*)> func = std::bind(&Airplaine::impress, std::placeholders::_1);
std::thread first(func, av1);
first.join();
functional
header is needed.
Or you can use a lambda function:
auto f = [](Airplaine* av) {av->impress(); };
std::thread first(f, av1);
In C++, How a std::thread can call a member function without creating an object?
how td_1 and td_2 called the member function operator() of class H without an object of class H?
td_1
and td_2
does create objects of type H
. Those objects are temporaries. Next, those supplied function object(which are temporaries in this case) are moved/copied into the storage belonging to the newly created thread of execution and invoked from there.
You can confirm this by adding a default constructor and move constructor inside class H
as shown below:
#include<iostream>
#include<thread>
class H {
public:
void operator()(){
printf("This is H(), I take no argument\n");
}
void operator()(int x){
printf("This is H(), I received %d \n",x);
}
//default constructor
H()
{
std::cout<<"default constructor called"<<std::endl;
}
//move constructor
H(H&&)
{
std::cout<<"move constructor called"<<std::endl;
}
};
int main(){
int param = 0xD;
std::thread td_1 = std::thread(H());
std::thread td_2 = std::thread(H(),param);
td_1.join();
td_2.join();
return 0;
}
The output of the above program is:
default constructor called
move constructor called
move constructor called
default constructor called
move constructor called
move constructor called
This is H(), I take no argument
This is H(), I received 13
Start thread with member function
#include <thread>
#include <iostream>
class bar {
public:
void foo() {
std::cout << "hello from member function" << std::endl;
}
};
int main()
{
std::thread t(&bar::foo, bar());
t.join();
}
EDIT:
Accounting your edit, you have to do it like this:
std::thread spawn() {
return std::thread(&blub::test, this);
}
UPDATE: I want to explain some more points, some of them have also been discussed in the comments.
The syntax described above is defined in terms of the INVOKE definition (§20.8.2.1):
Define INVOKE (f, t1, t2, ..., tN) as follows:
- (t1.*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is an object of type T or a reference to an object of
type T or a reference to an object of a type derived from T;- ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is not one of the types described in the previous
item;- t1.*f when N == 1 and f is a pointer to member data of a class T and t 1 is an object of type T or a
reference to an object of type T or a reference to an object of a
type derived from T;- (*t1).*f when N == 1 and f is a pointer to member data of a class T and t 1 is not one of the types described in the previous item;
- f(t1, t2, ..., tN) in all other cases.
Another general fact which I want to point out is that by default the thread constructor will copy all arguments passed to it. The reason for this is that the arguments may need to outlive the calling thread, copying the arguments guarantees that. Instead, if you want to really pass a reference, you can use a std::reference_wrapper
created by std::ref
.
std::thread (foo, std::ref(arg1));
By doing this, you are promising that you will take care of guaranteeing that the arguments will still exist when the thread operates on them.
Note that all the things mentioned above can also be applied to std::async
and std::bind
.
Thread calling a class function error
You are trying to pass a pointer to the method to the thread object(actually you have a syntax error, but I got your intention). It just can't work — it needs an associated object. You can use std::bind
to create a callable which you can then pass to the std::thread
object, like this:
thread t1(std::bind(&Cpu::Run_core2, &Cpu));
or, alternatively you can use a lambda function:
thread t1([&Cpu]{Cpu.Run_core2();}));
or, the best way is to use another std::thread ctor:
thread t1(&Cpu::Run_core2, &Cpu);
Do the same manipulations with the rest and that should work.
Threads calling function in another class
The constructor of std::thread
uses std::invoke
passing copies of the constructor parameters.
std::invoke
can, among other alternatives, be called with member function pointers. This requires syntax different to the one used in the question:
std::thread t1(
&VMGR::helloFunction, // member function pointer
vm, // pointer to the object to call the function for
20 // function parameter
);
std::thread t2(&VMGR::helloFunction, vm,30);
c++ std::thread calling method from object cause to calling destructor of this class
Since
std::thread
can't be sure that the value you passed to it will exists after creating the thread, it makes a copy of the value you passed.Another copy done by
decay_copy
, called instd::thread
's constructor.New instance.
You can have a detailled explanation of std::thread
's constructor here: https://en.cppreference.com/w/cpp/thread/thread/thread
C++ start thread with method of internal class
You are trying to pass nullptr
to the std::thread
constructor in B::B()
:
myTread = std::thread(nullptr);
Rewritten it to use the member initializer list and to let std::thread
be default constructed it could look like this:
B::B() : member_b{10}, myTread{}, myA{new A(5)} {}
C++11 multithreading with class member function
You need to pass two things: a pointer-to-member, and the object. You cannot call a non-static member function (like Gamma
) in C++ without an object. The correct syntax would be:
std::thread gamma_thread(&Beta::Gamma, // the pointer-to-member
my_beta, // the object, could also be a pointer
5); // the argument
You can think of my_beta
here as being the first argument to Gamma()
, and 5
as the second.
Related Topics
Initializer List Not Working with Vector in Visual Studio 2012
Variadic Template in VS 2012 (Visual C++ November 2012 Ctp)
Can Const-Correctness Improve Performance
Detect Windows or Linux in C, C++
Practical Uses for the "Curiously Recurring Template Pattern"
Opencv Tracking Using Optical Flow
Calling Functions in a Dll from C++
C++ Polymorphism Without Pointers
Reading and Writing a Std::Vector into a File Correctly
Visual Studio: Run C++ Project Post-Build Event Even If Project Is Up-To-Date
How to Cast a Derived Class to a Private Base Class, Using C-Style Cast
Copy Elision: Move Constructor Not Called When Using Ternary Expression in Return Statement
Differencebetween a Template Class and a Class Template
How to Correctly Use Cv::Triangulatepoints()
Is There Any Lame C++ Wrapper\Simplifier (Working on Linux MAC and Win from Pure Code)