I want my function running in a separate thread. I use Boost library and include like this in my main.cpp:
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
I want the thread start like this:
boost::thread ethread(Engine::function,info);
// info is an object from the class Engine and i need this in the
// function
My Engine class is in the func.h and the function looks like this:
void Engine::function(Engine info)
{
//STUFF
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}
BTW: Is the sleep function for the thread right?
Every time I want to compile it gives me this error:
error C3867: "Engine::function": function call missing argument list; use '&Engine::function' to create a pointer to member
I tried to use &Engine::function in the thread and this error appears:
error C2064: term does not evaluate to a function taking 2 arguments
I also tried:
boost::thread ethread(Engine::function,info, _1);
Then this error appeared:
error C2784: "result_traits<R,F>::type boost::_bi::list0::operator [](const boost::_bi::bind_t<R,F,L> &) const"
Can someone help me with this? I only want to run the function beside the main thread.
You should use bind function to create functional object with pointer to class member function or make your function static.
http://ru.cppreference.com/w/cpp/utility/functional/bind
More detailed explanation:
boost::thread constructor needs pointer to a function. In case of normal functions syntax is simple: &hello
#include <boost/thread/thread.hpp>
#include <iostream>
void hello()
{
std::cout << "Hello world, I'm a thread!" << std::endl;
}
int main(int argc, char* argv[])
{
boost::thread thrd(&hello);
thrd.join();
return 0;
}
But if you need pointer to a function of class you have to remember that such functions have implicit parameter - this pointer, so you have to pass it also. You can do this by creating callable object with std::bind, or boost bind.
#include <iostream>
#include <boost/thread.hpp>
class Foo{
public:
void print( int a )
{
std::cout << a << std::endl;
}
};
int main(int argc, char *argv[])
{
Foo foo;
boost::thread t( std::bind( &Foo::print, &foo, 5 ) );
t.join();
return 0;
}
Related
This question already has answers here:
Start thread with member function
(5 answers)
Closed 8 years ago.
i'm trying to use a function of a class with std::thread
The follow code snippet return an error
MyClass *MyClass_ptr = new MyClass;
MyClass_ptr->MyFunction(); // Works
std::thread ThreadA(MyClass_ptr->MyFunction() ); // Error here
std::thread ThreadB(MyClass_ptr->MyOtherFunction() ); // Error here
I need to make a thread with that specific pointer to the class: MyClass_ptr
So, is there a way to use a method of that class using this specific pointer ?
If it's useful here is the full code compiled with Microsoft Visual Studio 2013
#include "stdafx.h"
#include <iostream>
#include <thread>
class MyClass
{
public:
void MyFunction();
void MyOtherFunction();
};
void MyClass::MyOtherFunction()
{
std::cout << "Inside MyOtherFunction" << std::endl;
std::cin.get();
}
void MyClass::MyFunction ()
{
std::cout << "Inside MyFunction" << std::endl;
std::cin.get();
}
int _tmain(int argc, _TCHAR* argv[])
{
MyClass *MyClass_ptr = new MyClass;
MyClass_ptr->MyFunction(); // Works
std::thread ThreadA(MyClass_ptr->MyFunction() ); // Error here
std::thread ThreadB(MyClass_ptr->MyOtherFunction() ); // Error here
delete MyClass_ptr;
MyClass_ptr = nullptr;
return 0;
}
You need to pass an object on which the member function will be called (remember, every non-static member function has an implicit this parameter) :
#include <thread>
class MyClass
{
public:
void MyFunction();
void MyOtherFunction();
};
int main()
{
MyClass *MyClass_ptr = new MyClass;
std::thread ThreadA(&MyClass::MyFunction, MyClass_ptr);
std::thread ThreadB(&MyClass::MyOtherFunction, MyClass_ptr );
}
You could use a closure.
std::thread ThreadA( [MyClass_ptr](){
MyClass_ptr->MyFunction();
});
Yes you will need to use bind. The following example is for boost bind but you could always use the C++11 version of bind.You could use it like this
boost::thread t(boost::bind(&sommeclass::someMethod, ptr_instance_of_someclass,parameters_if_any));
so in your case it will be
boost::thread ThreadA(boost::bind(MyClass::MyFunction,MyClass_ptr));
I understand the std::thread notation presented here and reproduced as follows
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
void f1(int n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread " << n << " executing\n";
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
void f2(int& n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 2 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
int main()
{
int n = 0;
std::thread t1; // t1 is not a thread
std::thread t2(f1, n + 1); // pass by value
std::thread t3(f2, std::ref(n)); // pass by reference
std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
t2.join();
t4.join();
std::cout << "Final value of n is " << n << '\n';
}
because the definition of f1 and f2 is within main but fail to understand
#ifndef THREADED_H_
#define THREADED_H_
class Threadme
{
long count;
public:
Threadme();
void run(void);
void delay(long);
};
#endif
#include "threaded.h"
#include <iostream>
#include <chrono>
Threadme::Threadme() : count(0) {}
void Threadme::delay(long seconds)
{
std::chrono::steady_clock::time_point end_t = std::chrono::system_clock::now() + std::chrono::seconds(seconds);
while(std::chrono::system_clock::now() < end_t)
;
}
void Threadme::run(void)
{
while(count < 10)
{
++count;
std::cout << count << std::endl;
delay(1);
}
}
#include <cstdlib>
#include <thread>
#include "threaded.h"
int main(int argc, char *argv[]){
std::thread t1(&Threadme::run, Threadme());
t1.join();
return EXIT_SUCCESS;
}
specifically the expression std::thread t1(&Threadme::run, Threadme()); as it relates to defining the threaded function run outside of main. Why the reference & and why the thread parameters is a constructor invocation?
&Foo::mem where Foo is a class type and mem a member (function or value) of Foo, is C++ notation for obtaining a pointer to a member (function or value). There exist a special syntax for invoking a member function pointer on an object, but this is usually sugared away by using std::mem_fun, which will turn a member function pointer into an ordinary function where the first argument has to be an object of the type the member function was taken from.
std::thread understands what is happening here and does exactly that: invoke Foo::mem on the object passed as the second argument.
A small example to reproduce this locally without actually involving std::thread:
#include <functional>
class Foo { void mem() {} };
int main() {
Foo f;
f.mem(); // normal invoke
auto func = std::mem_fun(&Foo::mem);
func(std::ref(f)); // invoke mem on f
func(f); // invoke mem on a copy of f
func(&f); // invoke mem on f through a pointer
}
Why don't we need the mem_fun when constructing std::thread? It
automatically detects those situations through an overload and does
the right thing all by itself.
You can see a member function of ThreadMe as a function that accepts an implicit first parameter of type ThreadMe* - also known as this. This analogy is not 100% correct and might be shred to pieces by some language lawyer, but it serves for understanding the call you have there.
std::thread and many other classes/functions that accept functions and parameters for them, like e.g. std::bind and std::function accept pointers to member functions, followed by an object on which the function has to be called, or put otherwise, followed by that implicit first parameter.
So void ThreadMe::run() can be seen as void run(ThreadMe&); Then the call that bothers you is easy to understand. Consider your second example:
void f1(int n);
int n;
std::thread t2(f, n); //calls f in a new thread, passing n
now create the int just when it's needed:
std::thread t2(f, int()); //calls f, passing a copy of the int that has been created here...
with ints that might not make so much sense, but with an object it does:
void run(ThreadMe&);
std::thread t1(run, ThreadMe()); //conceptually the same as above
and since we know thet member functions are just a bit more than syntactic sugar for that implicit first argument, the call you have is still nothing else but the above:
void ThreadMe::run(); //implicit first argument is a ThreadMe&
std::thread t1(ThreadMe::run, ThreadMe()); //pass a copy of that newly created ThreadMe as the implicit first argument of the run method.
If you know lambdas, this is very similar, i.e. it passes a copy of a fresh ThreadMe to the thread that calls run on that copy::
ThreadMe threadMe;
std::thread t1([=](){ threadMe.run(); });
In fact, since the binding of parameters to functions that happens under the hood of std::thread's constructor is somewhat unusual, I prefer using lambdas, since they explain explicitly anything the thread has to do. In this case I would not create that temporary ThreadMe to call the thread, I would create a nontemporary inside the thread itself:
std::thread t1([](){
ThreadMe threadMe;
threadMe.run();
});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
pthread Function from a Class
I am fairly new to c++ and I am doing a project regarding TCP.
I need to create a thread so I googled and found this.
http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html
I follow its syntax but encounter errors:
argument of type ‘void* (ns3::TcpSocketBase::)()’ does not match ‘void* ()(void)’
codes:
tcp-socket-base.h:
class TcpSocketBase : public TcpSocket
{
public:
...
void *threadfunction();
....
}
tcp-socket-base.cc:
void
*TcpSocketBase::threadfunction()
{
//do something
}
..//the thread was create and the function is called here
pthread_t t1;
int temp = pthread_create(&t1, NULL, ReceivedSpecialAck, NULL); //The error happens here
return;
...
Any help would be appreciated. Thanks!
EDIT:
I took the advise and make the threadfunction a non member function.
namespaceXXX{
void *threadfunction()
int result = pthread_create(&t1, NULL, threadfunction, NULL);
NS_LOG_LOGIC ("TcpSocketBase " << this << " Create Thread returned result: " << result );
void *threadfunction()
{
.....
}
}
But I got this error instead:
initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)’ [-fpermissive]
If you'd like to continue using pthreads, a simple example is:
#include <cstdio>
#include <string>
#include <iostream>
#include <pthread.h>
void* print(void* data)
{
std::cout << *((std::string*)data) << "\n";
return NULL; // We could return data here if we wanted to
}
int main()
{
std::string message = "Hello, pthreads!";
pthread_t threadHandle;
pthread_create(&threadHandle, NULL, &print, &message);
// Wait for the thread to finish, then exit
pthread_join(threadHandle, NULL);
return 0;
}
A better alternative, if you're able to, is to use the new C++11 thread library. It's a simpler, RAII interface that uses templates so that you can pass any function to a thread, including class member functions (see this thread).
Then, the above exmaple simplifies to this:
#include <cstdio>
#include <string>
#include <iostream>
#include <thread>
void print(std::string message)
{
std::cout << message << "\n";
}
int main()
{
std::string message = "Hello, C++11 threads!";
std::thread t(&print, message);
t.join();
return 0;
}
Note how you can just pass data directly in - casts to and from void* are not needed.
You look to be passing a member function of a class to your pthread_create function. The thread function should be a non-member function that has the following signature
void *thread_function( void *ptr );
If you declare the function static it will compile.
I am trying to run the following program using boost::thread.
#include <boost/thread.hpp>
#include <iostream>
using namespace std;
class test{
public:
void hello(int i)
{
cout << i << " ";
};
};
int main(int argc, char* argv[])
{
class test t;
boost::thread thrd(t.hello, 10);
thrd.join();
return 0;
}
It is throwing an error while compiling as given below:
thread.c:17:33: error: no matching function for call to
'boost::thread::thread(, int)'
/usr/include/boost/thread/detail/thread.hpp:236:9: note: candidates
are: boost::thread::thread(F, A1) [with F = void (test::*)(int), A1 =
int] /usr/include/boost/thread/detail/thread.hpp:202:9: note:
boost::thread::thread(boost::detail::thread_move_t)
I am using boost 1.42. I have also tried old style boost::thread creation.
When hello() is not a class function, everything goes fine. Please let me know how can I fix it?
You didn't read the documentation.
You either need to make the hello method function static, or create thread by passing object of type test to it's constructor :
int main(int argc, char* argv[])
{
test t;
boost::thread thrd(&test::hello, &t, 10);
thrd2.join();
}
The problem is you are try to bind to a member function try the following (i don't have your boost version so have no idea if this works for sure)
boost::thread thrd(&test::hello, &t, 10);
Failing that you can use a binder
boost::thread thrd(
boost::bind(&test::hello, &t, 10));
If your compiler is new enough you can use the standard library equivalents of all of those by changing the boost namespace for std:: (the placeholder are in std::placeholders not the global namespace).
std::thread(... //c++11
Try with this code:
int main(int argc, char* argv[])
{
test t;
boost::thread thrd(&test::hello,&t,10);
thrd.join();
return 0;
}
I try to use boost::bind to create a function object, as well, I want to bind a object created on the HEAP to it for a delay call. The example code like below:
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/typeof/typeof.hpp>
#include <iostream>
using namespace boost;
class CTest : public noncopyable
{
public:
CTest():mInt(0){ std::cout << "constructor" << std::endl; }
~CTest(){ std::cout << "destructor" << std::endl; }
int mInt;
};
int getM( CTest * t )
{
return t->mInt;
}
function<int()> makeF()
{
// create some resource on HEAP, not on STACK.
// cause the STACK resource will be release after
// function return.
BOOST_AUTO( a , make_shared<CTest>() );
// I want to use bind to create a function call
// wrap the original function and the resource I create
// for delay call.
//
// I use shared_ptr to auto release the resource when
// the function object is gone.
//
// Compile ERROR!!!
// cannot convert parameter 1 from 'boost::shared_ptr<T>' to 'CTest *'
//
return bind<int>( getM , a );
}
int main(int argc, char* argv[])
{
BOOST_AUTO( delayFunc , makeF() );
delayFunc();
return 0;
}
The above is just a example code. But I think it shows what I want and the current error is.
Currently, I think I can only use a function object to wrap the original function like below:
class CGetM
{
public:
typedef int result_type;
int operator() ( shared_ptr<CTest> t )
{
return getM( t.get() );
}
};
And replace the code like this:
return bind<int>( CGetM() , a );
However, if currently I have many original function like getM, for adapting the correct arguments, wrapping it in a function object is really a large job. I don't know if there is some kind of tips or other useful util class in boost can handle such case more intelligently and elegantly ?
So any suggestion is appreciated. Thanks.
You need to use bind composition:
return bind<int>( getM, bind(&shared_ptr<CTest>::get, a) );