I have A timer class that I have set up to be able to bind to a free floating function using the std::function template. I would Like to modify the class to be able to support using both free floating functions and class member functions. I know that std::function can bind to a member function using std::bind but I am not sure how to set this up with the code I have:
#include <iostream>
#include <chrono>
#include <thread>
#include <functional>
#include <atomic>
namespace Engine {
template<class return_type,class...arguments>
class Timer{
typedef std::function<return_type(arguments...)> _function_t;
public:
Timer(size_t interval,bool autoRun,_function_t function,arguments...args){
_function = function;
_interval = interval;
if (autoRun) {
Enable(args...);
}
}
~Timer(){
if (Running()) {
Disable();
}
}
void Enable(arguments...args){
if (!Running()) {
_running=true;
enable(_interval, _function, args...);
}
}
void Disable(){
if (Running()) {
_running=false;
}
}
std::atomic_bool const& Running()const{
return _running;
}
protected:
void enable(size_t interval,_function_t func,arguments...args){
_thread =std::thread([&,func,interval,args...](){
std::chrono::duration<long long,std::nano> inter(interval);
auto __interval = std::chrono::microseconds(interval);
auto deadline = std::chrono::steady_clock::now();
while (_running) {
func(args...);
std::this_thread::sleep_until(deadline+=__interval);
}
});
_thread.detach();
}
protected:
_function_t _function;
std::atomic_bool _running;
size_t _interval;
std::thread _thread;
};
}
Any suggestions would be great. Let me know if I need to clarify anything.
Thanks
To pass a member function to this, pass a pointer to the unbound member function (&Engine::SceneManager::Update), and then the first parameter is a pointer to the object who should have the member called (a pointer to a SceneManager object, this is the "hidden" this pointer). This is how bind works, so no changes are needed to your code. As a simple alternative, pass a lambda.
http://coliru.stacked-crooked.com/a/7c6335d4f94b9f93 (though it isn't running as expected and I don't know why)
Also, I'm confused by the fact your code takes interal as a size_t, then converts it to nanoseconds, then converts that to microseconds, and then uses it. Why not just use microseconds the whole way through?
Your destructor has a race condition. Disable should stall until the thread has finished executing. I haven't used std::thread much, but I'd guess one place to start is if (_thread.is_joinable()) _thread.join(); As part of this, it might be useful to have the thread only sleep for 100ms at a time or so, and periodically check if it's supposed to be shutting down.
Enable should stop the existing thread, before starting a new one. Better yet, reuse the same thread. Unfortunately, there's no easy way to have an existing thread switch tasks, so it's easiest to simply Disable and then keep your existing code.
Related
Is there a better way to use CreateThread than creating a free function each time for the sole purpose of casting lpParameter?
Are there any modern alternatives to CreateThread for creating persistent threads?
Edit: Perhaps you should just use std::async(lambda). I imagine that it's just implemented with CreateThread. Maybe the answer to this question is looking up how std::async is implemented (assuming it's a library feature).
DWORD WINAPI MyThreadFunction(
_In_ LPVOID lpParameter
)
{
((MyClass*)lpParameter)->RunLoop();
}
void MyClass::LaunchThread()
{
CreateThread(
NULL, // default security attributes
0, // use default stack size
MyThreadFunction, // thread function name
this, // argument to thread function
0, // use default creation flags
NULL); // returns the thread identifier
}
There are several mechanisms for achieving parallelism (std::async etc. as mentioned above).
But the modern one which is most similar to your original code with CreateThread is std::thread. It can be constructed with a global function, a lambda, or a class method (which seems the best fit for you):
m_thread = std::thread([this](){ RunLoop(); }); // pass a lambda
or
m_thread = std::thread(&MyClass::RunLoop, this); // pass a method
Note that a std::thread starts to run (potentially) when constructed. Also note that, std::async does not guarantee that it will run on a separate thread and even if it does run on a thread, it could be a thread from a pool. The behaviour might not be the same as with your original CreateThread.
Here's a complete example of using std::thread (including cancellation):
#include <thread>
#include <chrono>
#include <atomic>
#include <iostream>
class MyClass
{
public:
MyClass() {}
~MyClass() { EndThread(); }
void LaunchThread()
{
EndThread(); // in case it was already running
m_bThreadShouldExit = false;
// Start the thread with a class method:
m_thread = std::thread(&MyClass::RunLoop, this);
}
void EndThread()
{
// Singal the thread to exit, and wait for it:
m_bThreadShouldExit = true;
if (m_thread.joinable())
{
m_thread.join();
}
}
void RunLoop()
{
std::cout << "RunLoop started" << std::endl;
while (!m_bThreadShouldExit)
{
std::cout << "RunLoop doing something ..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
std::cout << "RunLoop ended" << std::endl;
}
private:
std::thread m_thread;
std::atomic_bool m_bThreadShouldExit{ false };
};
int main()
{
MyClass m;
m.LaunchThread();
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
m.EndThread();
}
Possible output:
RunLoop started
RunLoop doing something ...
RunLoop doing something ...
RunLoop doing something ...
RunLoop doing something ...
RunLoop doing something ...
RunLoop ended
std::async() and std::thread(, <args...>) are most likely internally implemented as you just did, the only exception is that lambdas without captures can be implicitly converted to function pointers, which pretty much can be passed straight away to CreateThread function with nullptr lpParameter.
Lambdas with capture list are pretty much syntactic sugar but internally they translate to sth like this (very simplified):
struct <internal_lambda_name>
{
<capture list...> fields...;
void operator()(<arguments...>){<code...>;}
};
So they pretty much translate to objects of struct type thus they need some way to store all those captures and in order to be executed on other thread with CreateThread function they need some way of ensuring that the capture list data stored in them will be available during their execution.
I looked in to MSVC implementation of std::async and they implemented it using ::Concurrency::create_task which straight forwardly accepts a callable object.
https://learn.microsoft.com/en-us/cpp/parallel/concrt/task-parallelism-concurrency-runtime
I also looked into their implementation of create_task
template<typename _Ty>
__declspec(noinline) // Ask for no inlining so that the _CAPTURE_CALLSTACK gives us the expected result
explicit task(_Ty _Param)
{
task_options _TaskOptions;
details::_ValidateTaskConstructorArgs<_ReturnType,_Ty>(_Param);
_CreateImpl(_TaskOptions.get_cancellation_token()._GetImplValue(), _TaskOptions.get_scheduler());
// Do not move the next line out of this function. It is important that _CAPTURE_CALLSTACK() evaluates to the call site of the task constructor.
_SetTaskCreationCallstack(_CAPTURE_CALLSTACK());
_TaskInitMaybeFunctor(_Param, decltype(details::_IsCallable(_Param,0))());
}
and so it turns out that launching a lambda on a new thread is quite difficult and beyond the scope of this question.
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);
}
I want to implement a thread that can accept function pointers from a main thread and execute them serially. My idea was to use a struct that keeps the function pointer and its object and keep pushing it to a queue. This can be encapsulated in a class. The task thread can then pop from the queue and process it. I also need to synchronize it(so it doesnt block the main thread?), so I was thinking of using a semaphore. Although I have a decent idea of the structure of the program, I am having trouble coding this up, especially the threading and semaphore sync in C++11. It'd be great if someone can suggest an outline by which I can go about implementing this.
EDIT: The duplicate question answers the question about creating a thread pool. It looks like multiple threads are being created to do some work. I only need one thread that can queue function pointers and process them in the order they are received.
Check this code snippet, I have implemented without using a class though. See if it helps a bit. Conditional variable could be avoided here, but I want the reader thread to poll only when there is a signal from the writer so that CPU cycles in the reader won't be wasted.
#include <iostream>
#include <functional>
#include <mutex>
#include <thread>
#include <queue>
#include <chrono>
#include <condition_variable>
using namespace std;
typedef function<void(void)> task_t;
queue<task_t> tasks;
mutex mu;
condition_variable cv;
bool stop = false;
void writer()
{
while(!stop)
{
{
unique_lock<mutex> lock(mu);
task_t task = [](){ this_thread::sleep_for(chrono::milliseconds(100ms)); };
tasks.push(task);
cv.notify_one();
}
this_thread::sleep_for(chrono::milliseconds(500ms)); // writes every 500ms
}
}
void reader()
{
while(!stop)
{
unique_lock<mutex> lock(mu);
cv.wait(lock,[]() { return !stop;});
while( !tasks.empty() )
{
auto task = tasks.front();
tasks.pop();
lock.unlock();
task();
lock.lock();
}
}
}
int main()
{
thread writer_thread([]() { writer();} );
thread reader_thread([]() { reader();} );
this_thread::sleep_for(chrono::seconds(3s)); // main other task
stop = true;
writer_thread.join();
reader_thread.join();
}
Your problem has 2 parts. Storing the list of jobs and manipulating the jobs list in a threadsafe way.
For the first part, look into std::function, std::bind, and std::ref.
For the second part, this is similar to the producer/consumer problem. You can implement a semaphore using std::mutexand std::condition_variable.
There's a hint/outline. Now my full answer...
Step 1)
Store your function pointers in a queue of std::function.
std::queue<std::function<void()>>
Each element in the queue is a function that takes no arguments and returns void.
For functions that take arguments, use std::bind to bind the arguments.
void testfunc(int n);
...
int mynum = 5;
std::function<void()> f = std::bind(testfunction, mynum);
When f is invoked, i.e. f(), 5 will be passed as argument 1 to testfunc. std::bind copies mynum by value immediately.
You probably will want to be able to pass variables by reference as well. This is useful for getting results back from functions as well as passing in shared synchronization devices like semaphores and conditions. Use std::ref, the reference wrapper.
void testfunc2(int& n); // function takes n by ref
...
int a = 5;
std::function<void()> f = std::bind(testfunction, std::ref(a));
std::function and std::bind can work with any callables--functions, functors, or lambdas--which is pretty neat!
Step 2)
A worker thread dequeues while the queue is non-empty. Your code should look similar to the producer/consumer problem.
class AsyncWorker
{
...
public:
// called by main thread
AddJob(std::function<void()> f)
{
{
std::lock_guard<std::mutex> lock(m_mutex);
m_queue.push(std::move(f));
++m_numJobs;
}
m_condition.notify_one(); // It's good style to call notify_one when not holding the lock.
}
private:
worker_main()
{
while(!m_exitCondition)
doJob();
}
void doJob()
{
std::function<void()> f;
{
std::unique_lock<std::mutex> lock(m_mutex);
while (m_numJobs == 0)
m_condition.wait(lock);
if (m_exitCondition)
return;
f = std::move(m_queue.front());
m_queue.pop();
--m_numJobs;
}
f();
}
...
Note 1: The synchronization code...with m_mutex, m_condition, and m_numJobs...is essentially what you have to use to implement a semaphore in C++'11. What I did here is more efficient than using a separate semaphore class because only 1 lock is locked. (A semaphore would have its own lock and you would still have to lock the shared queue).
Note 2: You can easily add additional worker threads.
Note 3: m_exitCondition in my example is an std::atomic<bool>
Actually setting up the AddJob function in a polymorphic way gets into C++'11 variadic templates and perfect forwarding...
class AsyncWorker
{
...
public:
// called by main thread
template <typename FUNCTOR, typename... ARGS>
AddJob(FUNCTOR&& functor, ARGS&&... args)
{
std::function<void()> f(std::bind(std::forward<FUNCTOR>(functor), std::forward<ARGS&&>(args)...));
{
std::lock_guard<std::mutex> lock(m_mutex);
m_queue.push(std::move(f));
++m_numJobs;
}
m_condition.notify_one(); // It's good style to call notify_one when not holding the lock.
}
I think it may work if you just used pass-by-value instead of using the forwarding references, but I haven't tested this, while I know the perfect forwarding works great. Avoiding perfect forwarding may make the concept slightly less confusing but the code won't be much different...
I have the following class (dumbed down for the example, of course):
class file_handler_c {
public:
err_t init(int msecs);
err_t write(byte* buffer);
}
This class requires init to be called before any writes and then you can use this class to write to a file. However, after msecs milliseconds have passed, write stops writing to the file and returns an error.
My question is - how do you create a fast unit test for this behavior? Any small enough value will create a non-deterministic test that will sometimes fail due to other processes running on the machine. However, I want tests to be as fast as possible and not include any sleep or similar. I am using Google Test and Google Mock.
First of all I have to divert a little bit from your actual question. Please don't create interfaces like that. Whenever an object has been created, all its functions have to be callable until its lifetime ends. Informal lifetime constraints like "init() has to be called before write()", or even worse "always call close() before the destructor" can not be checked by the compiler and therefore are error prone.
Therefore I don't think, you should try to solve that issue in the test, but in the design of the code under test. Whenever it is hard to write a test, it is a sure bet, that your interfaces are flawed.
My suggestion is to separate timing and writing. Create a timer class like e.g. this one:
#include <memory>
#include <chrono>
template<typename T>
class Timer {
private:
std::chrono::milliseconds time_to_live;
std::shared_ptr<T> timed_object;
public:
template<typename... Arg>
Timer(std::chrono::milliseconds ttl, Arg... args):
time_to_live{ttl},
timed_object{std::make_shared<T>(args...)} {};
std::weak_ptr<T> get() { return {timed_object}; };
// ...
// when the defined time is over, timed_object will be set to nullptr somehow.
};
Use it like this:
#include <chrono>
#include <iostream>
#include <fstream>
int main(int, char**)
{
using namespace std::literals::chrono_literals;
auto timed_ostream = Timer<std::ofstream>{42ms, "filename"};
if( !timed_ostream.get().expired() ) {
// os is a shared_ptr. That guarantees, that the ostream will not
// be closed while you are still writing.
auto os = timed_ostream.get().lock();
(*os) << "whatever";
} // now os will be destroyed. The ofstream might be destroyed
// as well now, when the 42ms are over.
} // OK, here we destroy the timer and therefore the ofstream,
// if it is still alive.
With that interface you can easily write a simple test case with something else than an ostream, e.g. an int:
#include <chrono>
#include <cassert>
using namespace std::literals::chrono_literals;
void test_timed_object_valid_after_init()
{
auto clock = std::chrono::high_resolution_clock{};
auto start = clock.now();
auto timed_int = Timer<int>{2000ms,42}; // valid for 2000ms
assert(timed_int.get().expired()); // should still be here
} // The timer will be destroyed here. That destroys the shared_ptr
// and the object as well. The long lifetime does not matter.
void test_timed_object_invalid_after_time()
{
auto clock = std::chrono::high_resolution_clock{};
auto start = clock.now();
auto timed_int = Timer<int>{1ms,42}; // valid for 1ms
// you did not want sleep(), so we do busy waiting.
// Prefer usleep() instead.
// busy wait 1ms as exactly as possible.
while( clock.now() - start < 1ms ) {}
assert(timed_int.get().expired()); // should be gone now.
}
Note, that each testcase checks one single scenario here. Don't try and test the two requirements in a single test case. Then you either have to take a long lifetime for your object to check safely that it is there after initialization, or choose a short lifetime to check it is gone afterwards.
Beware: all the code in this posting should compile, but there might of course still be bugs somewhere. These are left as an exercise for the student ;-)
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;
}