I would like invoke a function call in a one shot manner. What's the best way to do this in Boost / C++?
I would like to pass it two parameters and do not need a result.
Well you can spin up a thread and then never join it again. Something like:
boost::thread some_thread(&SomeFunction, param1, param2);
Once the some_thread variable goes out of scope, the thread of execution will be detached and will not be able to be joined again. It's a waste to spin up a thread unless the processing time of this function is significant though.
I haven't used boost::thread in awhile but I see a quick example on the documentation page for the class:
void find_the_question(int the_answer);
boost::thread deep_thought_2(find_the_question,42);
I believe as soon as it finishes the function, the thread will exit. This may not be what you want in that once the thread goes out of scope, it will be destroyed. If that's not going to work, you probably need to create a long running thread pool and then pass your functors as boost::bind compositions.
Depending on how often you are doing this, you might be best off creating a pool of threads, along with a work queue. Creating a thread can create a lot of overhead if you are trying to do it dozens of times a second. If you don't care about the return value, that makes it really easy.
Spin up a thread or two (or ten); have a thread-safe queue of functors to call (bind the parameters to the function and put that on the queue); the threads wait on the queue for something to show up, the first thread to wake up gets to process the work. When a thread is done running a job, it waits on the queue again.
Take a look at this project for an idea of one way to do it.
Of course if you are only making asynchonous calls every couple of seconds to improve a UI's responsiveness, it'd be easier to just start up a new thread every time.
Perhaps you want to emit a signal?
I really liked Qt's signals and slots functionality, and I know Boost has signals/slots as well. I've never used signals/slots in Boost, though.
Related
I want to execute a function asynchronously and not wait for it to complete. I initially thought I could use std::async with launch::async, but the returned future's destructor blocks until the function is complete.
Is there a way of running a function on a thread pool using stl without blocking?
You should spawn a single new thread which waits on a counting semaphore. When it is awoken (unblocked), it will send one RPC request and decrement the counter. When the user clicks the button, increment the counter. The same thread can service all requests throughout the program's lifetime.
You're looking for std::thread::detach. http://en.cppreference.com/w/cpp/thread/thread/detach
You can create a thread, and then detach from it. At that point you can delete your thread handle and the thread will run without you.
Incidentally it's usually considered bad form to use this technique. Generally you should care about the state of the thread, and should try to shut it down gracefully at program end, but in practice this is a useful trick for when you really don't care.
This proposal talks about executors... it looks like the kind of thing I was hoping I'd find existed already, but it looks like it doesn't.
http://isocpp.org/files/papers/n4039.html
Like a good deal of other people, I too am currently working on a little wrapper class for boost::thread and facing the problem to write a simple sleep(int miliseconds) function that can be called from another thread. Just like boost::thread::sleep() used to do. Since that function is going to be discontinued soon, there are new options: boost::this_thread::sleep_for() and sleep_until(). But I don't see how I could manage to achieve the wanted behaviour with those. And I also couldn't find a solution yet, even though this seems to be an issue to lots of people.
So I have my ThreadWrapper class with a boost::thread working inside. What I want to do is this:
ThreadWrapper thread(func_foo);
Thread.sleep(100); //tells the underlying boost:thread of my Threadwrapper
//to sleep 100ms
Any suggestions? Thanks!
Seems to me this is application specific... like where in the target thread should a sleep occur? Let's say you've got a thread awaiting socket data... it's effectively already sleeping... do you want it to sleep some more when data actually arrives? Or stop waiting for data? Or maybe you have a thread crunching numbers... you may want it to sleep after a block of work. So, it seems to me you could have a simple class method setToPause(int ms) which sets a member sleeper value, then your worker/target thread checks the value at opportune times and resets and sleeps if it's set (or sleeps then resets, depending on your requirements). Not sure if that solves your specific problem (or even what that is) but it has to be easier than trying to poke around with thread scheduling...
How efficient is the call to std::async? Can it be used to issue a task in a game loop?
I want all my input detection to be on a separate thread and synced at a certain point in the game loop in my main thread so that I can poll for input.
The only way I can think of doing this is to split up my tasks for input detection and call them using std::async at the beginning of the actual game loop and then call wait() later in the loop to sync the data, but I want that same behavior EVERY iteration of the loop so this call must be expensive...
Is that the way?
Assuming it's well written then std::async(std::launch::async, ...) should be no more expensive than a small heap allocation and constructing a std::thread. If creating a new std::thread to do the work is efficient enough for you, then std::async will be efficient enough but will save you the trouble of writing the synchronisation to get the result back to the main thread.
If creating a new std::thread for each piece of work is not appropriate, then std::async might not be either.
(N.B. remember that unless you specify std::launch::async as the launch policy there's no guarantee the task executes asynchronously, it might be deferred until you call get() on the returned future.)
At least IMO, you should make up your mind between polling and asynchronous operation.
If you're going to poll, then using std::async is redundant. You're going to poll from the main thread anyway, so you might as well just have it directly poll for what it cares about and be done with it. Using std::async to launch something else will simply add a delay in getting the data to the main thread.
If you're going to use std::async, then you should take a rather different approach: the threads that get the input act independently. When they find some input, they send it to the main thread, and tell it that it has some input to process (e.g., by setting a semaphore). Then the main thread reacts to that semaphore, retrieves the input data (e.g., from a queue) and processes it.
In the latter case, polling is pointless: if the input thread hasn't told the main thread about some input data, then there simply isn't any. That being the case, polling for input data is pointless -- you already know there is none.
Is there any way, by which we can Re-Initialize a thread without killing it. I want to use the existing thread, but they will again start from the beginning.
Create a class that manages a thread.
In the run method of this class have it wait until some work is assigned to the class in the form of a function pointer or some other class that implements a "work" interface.
Once work is assigned, the thread can stop waiting and execute the work.
Once the work is complete the thread sits and waits until more work is assigned to it.
This allows you to keep the thread running and waiting for work, without having to recreate it when new work comes along.
What y ou are asking for can only be achieved by the logic of your thread function. The thread library/operating system does not know about your logic and cannot possibly know where you want it to go on reinitialization.
Also note that while you can achieve something similar by canceling and starting the thread, thread cancellation is quite often dangerous (you might leak resources) if even possible (thread must hit a cancellation point) and should be avoided in most cases. So you are back at square one: implement logic in the function to detect the event and restart with whatever definition of start you want to use.
You could have two events: restart and stop. Your thread function would wait in a loop for any of them. If it detects restart, it would perform the task and go back waiting for events. If it detects stop, it would simply return.
I want to provide a global io_service that is driven by one global thread. Simple enough, I just have the thread body call io_service::run(). However, that doesn't work as run (run_one, poll, poll_one) return if there is no work to do. But, if the thread repeatedly calls run(), it will busy loop when there is nothing to do.
I'm looking for a way to get the thread to block while there isn't any work to be done in the io_service. I could add a global event to the mix for the thread to block on. However, that would require users of the io_service to notify the event every time they used the service. Not the ideal solution.
Note: there are no actual globals and I never use events for concurrency I just simplified the problem down to my exact need. The real goal is a asio::deadline_timer subclass that doesn't require an io_service as a construction parameter.
You need to create an io_service::work object.
See this section of the documentation:
Stopping the io_service from running out of work