how to run a static function in a new thread? - c++

After searching trough the forum, i came across some answers nevertheles I could not get a clear answer to how to run a static method in a new thread in c++. My main concern is what is the best way to start a thread?(Is it working also from inside of another thread?)
which header is better to use? thread.h, pthread.h?
I would like to create a new thread(when a given method is called) and call inside this thread another function...
Any hints how I could approach this issue?
Thank you guys very much in advance!

There is no problem to run static member function in thread. Just use std::thread the same way as for free function:
#include <thread>
class Threaded
{
public:
static void thread_func() {}
};
int main()
{
std::thread t(Threaded::thread_func);
t.join();
return 0;
}
Of course, starting thread will work from any other thread as well. With C++11 standard compliant compiler you shall use #include <thread>. Otherwise take a look at boost::thread. It's usage is similar.

Assuming for example your static function has two parameters:
#include <boost/thread/thread.hpp>
void launchThread()
{
boost::thread t( &MyClass::MyStaticFunction, arg1, arg2 );
}
This will require linking to the Boost.Thread library.

The best OOPs way of doing this would be:
Define an entry point (entryPoint()) which will call a member function(myThreadproc()). The entry point will start the thread and call myThreadproc. Then you can access all the member variables and methods.
myClassA.h
class A
{
static void *entryPoint(void *arg);
void myThreadproc();
void myfoo1();
void myfoo2();
}
myClassA.cpp
void *A::entryPoint(void *arg)
{
A *thisClass = (A *)arg;
thisClass-> myThreadproc();
}
void A::myThreadproc()
{
//Now this function is running in the thread..
myfoo1();
myfoo2();
}
Now you can create the thread like this:
int main()
{
pthread_t thread_id;
pthread_create(&thread_id,NULL,(A::entryPoint),new A());
//Wait for the thread
return 0;
}

Related

C++ Multithreading methods in an object with infinite loops

I never did any C++ or multithreading before and need help about something.
Let's suppose I have this in my hpp file.
Class Test{
public:
struct type_something_to_kill_the_foo_thread something_to_kill_the_foo_thread;// I don't know what
void foo(stuff stuff){
while(true) does_stuff(stuff);
}
void thread_foo(stuff stuff){
std::thread th = (&Test::foo, this, stuff);
something_to_kill_the_foo_thread = th; // or th.getid() any mechanism so that I can invoke a function to destroy the thread
sleep(MAX_INT);
}
}
And I have this in my main.
Test t = Test();
t.thread_foo("random stuff1");
t.thread_foo("random stuff2");
...
How can I parallelize these two calls without using a thread in my main so my main keeps going ? Where do I put my join() if I need one and how to destroy the first thread ?
I have been having a hard time with online tutorials as they always call std::thread in the main().
That's how you make a thread:
#include <thread>
int main() {
Test t = Test();
std::thread(t.thread_foo, "random stuff1").detach()
std::thread(t.thread_foo, "random stuff2").detach()
// Works in parallel
}

c++ timer terminate without an active exception?

I want to design a timer in c++, to execute my function after a fixed time.
the code likes like:
#include <thread>
typedef void (*callback)();
class timer {
public:
void start(int sec, callback f) {
std::thread t([&sec, &f]() {sleep(sec); f();});
}
};
void test () {
printf("here called\n");
}
int main() {
timer t;
t.start(3, test);
while (1);
}
but when i run this code, i got:
terminate called without an active exception
[1] 3168208 abort (core dumped) ./a.out
can you help on this? and, any suggestions for a more flexible timer design?
You created a std::thread and destructed it without detaching it.
std::thread t([&sec, &f]() {sleep(sec);
Either call join to wait on it, or call detach.
Note also the capture by reference issue in your comments.
There are a few problems with your code that need to be addressed:
After spawning a std::thread you need to synchronize it using std::thread::join().
Remove the reference capture from the sec parameter in order to prevent dangling of references by the end of the scope of start().
sleep() is platform-dependent, so your code will only work for certain platforms that support it. Instead use, std::this_thread::sleep_for(std::chrono::seconds(sec));
#include <thread>
#include <chrono> // For std::chrono
#include <cstdio> // For printf
typedef void (*callback)();
class timer {
// Bring the thread object outside the function and make it an instance variable of the class
std::thread t;
public:
// Spawns a thread
void start(int const sec, callback&& f) {
if (t.joinable()) // If the object already has a thread attached to it, call 'join()' on it
t.join();
/* Capture 'sec' by value as it is a local variable, consequently, capture
'f' by reference as it is a function and its lifetime is throughout the whole
program */
t = std::thread([sec, &f]() {
std::this_thread::sleep_for(std::chrono::seconds(sec));
f();
});
}
// After the class gets destroyed, the thread is synchronized
~timer() {
t.join();
}
};
void test () {
printf("here called\n");
}
int main() {
timer t;
t.start(3, test);
}

Boost Scoped Pointer To Boost Thread

Today I want to use a boost::scoped_ptr to point to a boost::thread.
In my Thread.h I have boost::scoped_ptr<boost::thread> m_thread and in my Thread.cpp there's a function create() in which the creation of the boost::thread should take place.
I tried Thread::m_thread (new boost::thread(attr, boost::bind(%Thread::run, this))); but unsurprisingly it didn't work.
I can't figure out myself (or by using the boost documentation) how I would do this, since I don't fully understand what's happening with the scoped_ptr and how it works.
Before I used to use a raw pointer, which worked fine but I'm not allowed to use it at this point.
Thanks for your time!
I don't know what kind of error your got, try this:
class Thread {
public:
Thread() : thread_(new boost::thread(boost::bind(&Thread::run, this))) {
}
void run() {
}
~Thread() {
thread_->join();
}
private:
boost::scoped_ptr<boost::thread> thread_;
};
int main() {
Thread thread;
}
But do not forget, that thread may start before constructor end his job.

How to schedule member function for execution in boost::threadpoool

I found a threadpool which doesn't seem to be in boost yet, but I may be able to use it for now (unless there is a better solution).
I have several million small tasks that I want to execute concurrently and I wanted to use a threadpool to schedule the execution of the tasks. The documentation of the threadpool provides (roughly) this example:
#include "threadpool.hpp"
using namespace boost::threadpool;
// A short task
void task()
{
// do some work
}
void execute_with_threadpool(int poolSize, int numTasks)
{
// Create a thread pool.
pool tp(poolSize);
for(int i = 0; i++; i < numTasks)
{
// Add some tasks to the pool.
tp.schedule(&task);
}
// Leave this function and wait until all tasks are finished.
}
However, the example only allows me to schedule non-member functions (or tasks). Is there a way that I can schedule a member function for execution?
Update:
OK, supposedly the library allows you to schedule a Runnable for execution, but I can't figure out where is the Runnable class that I'm supposed to inherit from.
template<typename Pool, typename Runnable>
bool schedule(Pool& pool, shared_ptr<Runnable> const & obj);
Update2:
I think I found out what I need to do: I have to make a runnable which will take any parameters that would be necessary (including a reference to the object that has a function which will be called), then I use the static schedule function to schedule the runnable on the given threadpool:
class Runnable
{
private:
MyClass* _target;
Data* _data;
public:
Runnable(MyClass* target, Data* data)
{
_target = target;
_data = data;
}
~Runnable(){}
void run()
{
_target->doWork(_data);
}
};
Here is how I schedule it within MyClass:
void MyClass::doWork(Data* data)
{
// do the work
}
void MyClass::produce()
{
boost::threadpool::schedule(myThreadPool, boost::shared_ptr<Runnable>(new Runnable(myTarget, new Data())));
}
However, the adaptor from the library has a bug in it:
template<typename Pool, typename Runnable>
bool schedule(Pool& pool, shared_ptr<Runnable> const & obj)
{
return pool->schedule(bind(&Runnable::run, obj));
}
Note that it takes a reference to a Pool but it tries to call it as if it was a pointer to a Pool, so I had to fix that too (just changing the -> to a .).
To schedule any function or member function - use Boost.Bind or Boost.Lambda (in this order). Also you can consider special libraries for your situation. I can recommend Inter Threading Building Blocks or, in case you use VC2010 - Microsoft Parallel Patterns Library.
EDIT:
I've never used this library or heard anything bad about it, but it's old enough and still is not included into Boost. I would check why.
EDIT 2:
Another option - Boost.Asio. It's primarily a networking library, but it has a scheduler that you can use. I would use this multithreading approach. Just instead of using asynchronous network operations schedule your tasks by boost::asio::io_service::post().
I think I found out what I need to do: I have to make a runnable which will take any parameters that would be necessary (including a reference to the object that has a function which will be called), then I use the static schedule function to schedule the runnable on the given threadpool:
class Runnable
{
private:
MyClass* _target;
Data* _data;
public:
Runnable(MyClass* target, Data* data)
{
_target = target;
_data = data;
}
~Runnable(){}
void run()
{
_target->doWork(_data);
}
};
Here is how I schedule it within MyClass:
void MyClass::doWork(Data* data)
{
// do the work
}
void MyClass::produce()
{
boost::threadpool::schedule(myThreadPool, boost::shared_ptr<Runnable>(new Runnable(myTarget, new Data())));
}
However, the adaptor from the library has a bug in it:
template<typename Pool, typename Runnable>
bool schedule(Pool& pool, shared_ptr<Runnable> const & obj)
{
return pool->schedule(bind(&Runnable::run, obj));
}
Note that it takes a reference to a Pool but it tries to call it as if it was a pointer to a Pool, so I had to fix that too (just changing the -> to a .).
However, as it turns out, I can't use that boost thread pool because I am mixing native C++ (dll), C++/CLI (dll) and .NET code: I have a C++/CLI library that wraps a native C++ library which in tern uses boost::thread. Unfortunately, that results in a BadImageFormatException at runtime (which has previously been discussed by other people):
The problem is that the static boost thread library tries to hook the
native win32 PE TLS callbacks in order to ensure that the thread-local
data used by boost thread is cleaned up correctly. This is not
compatible with a C++/CLI executable.
This solution is what I was able to implement using the information: http://think-async.com/Asio/Recipes. I tried implementing this recipe and found that the code worked in Windows but not in Linux. I was unable to figure out the problem but searching the internet found the key which was make the work object an auto pointer within the code block. I've include the void task() that the user wanted for my example I was able to create a convenience function and pass pointers into my function does the work. For my case, I create a thread pool that uses the function : boost::thread::hardware_concurrency() to get the possible number of threads. I've used the recipe below with as many as 80 tasks with 15 threads.
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/scoped_ptr.hpp>
// A short task
void task()
{
// do some work
}
void execute_with_threadpool( int numTasks,
int poolSize = boost::thread::hardware_concurrency() )
{
boost::asio::io_service io_service;
boost::thread_group threads;
{
boost::scoped_ptr< boost::asio::io_service::work > work( new boost::asio::io_service::work(io_service) );
for(int t = 0; t < poolSize; t++)
{
threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
}
for( size_t t = 0; t < numTasks; t++ )
{
++_number_of_jobs;
io_service.post(boost::bind(task) );
}
}
threads.join_all();
}
Figured it out, you must have run() method defined, this is the easiest way:
class Command
{
public:
Command() {}
~Command() {}
void run() {}
};
In main(), tp is your threadpool:
shared_ptr<Command> pc(new Command());
tp.schedule(bind(&Command::run, pc));
Done.

[C++]Would this be a valid approach for a 'sleep' function in a thread?

I would like to implement a sleep() function in my thread class, but I don't know if this is a valid/proper way to do it.
This is my entire thread class (thread.h):
#include <process.h>
struct RUNNABLE{
virtual void run() = 0;
};
class thread{
public:
void start(void *ptr){
DWORD thr_id;
HANDLE thr_handl = (HANDLE)_beginthreadex(NULL, 0, thread_proc, ptr, 0, (unsigned int*)&thr_id);
}
void sleep(int sleep_time, bool alertable){
SleepEx(sleep_time, alertable);
}
private:
static unsigned int __stdcall thread_proc(void *param){
((RUNNABLE*)param)->run();
_endthreadex(0);
return 0;
}
};
And as you're probably able to sort out, this is my sleep() function:
void sleep(int sleep_time, bool alertable){
SleepEx(sleep_time, alertable);
}
But will this make the actual thread contained inside this thread instance sleep for the specified amount of milliseconds?
Best regards,
Benjamin :).
EDIT:
So according to atzz, I could define the sleep function as a static member function, and have that call ::SleepEx(), and that would allow me to call it like this:
class test : RUNNABLE{
virtual void run(){
printf("hi");
thread::sleep(1000, false);
}
};
and then that'll cause the thread executing the 'test' runnable to sleep 1000 milliseonds?
It will put to sleep whichever thread calls this member function.
No, this will put the original thread to sleep, not the one you start.
Yes it will -- provided that it's called from that thread (i.e. from within thread::run()).
Due to this, I'd recommend making sleep() a protected member function.
Or, as an alternative, make it a static method, with semantics of thread::sleep() being a service that pauses calling thread (this approach is used, e.g., in Java standard library).
It is not possible to make an other than calling thread sleep, because the thread can be in the middle of something at that moment.
If you need to suspend newly created thread, you should use SuspendThread instead or pass CREATE_SUSPENDED to _beginthreadex(), but this can cause deadlocks in some cases
see http://msdn.microsoft.com/en-us/library/ms686345%28v=VS.85%29.aspx