I want to run some bunch of codes asynchronously in c++. This is for an gtk GUI application. I want to get the length from a encoder to an variable while running the other parts of the code. This lines of code should be always running. When i want the length, i should be able to get the current length from the variable. Can any one help me on this.
I haven't understood what exactly you want to do. But I think you can read more about the std::async.
#include <iostream>
#include <future>
void asyncFunction ()
{
std::cout << "I am inside async function\n";
}
int main()
{
std::future<void> fn = std::async(std::launch::async, asyncFunction);
// here some other main thread operations
return 0;
}
Function that is run asynchronously can also return a value, which can be accessed through the future with std::future::get blocking method.
Related
This question already has answers here:
When to use std::async vs std::threads?
(5 answers)
Closed 1 year ago.
I am trying to understand how exactly async differs from using threads. On a conceptual level, I thought multithreading was by definition asynchronous, because you are doing context switches between threads for things like I/O.
But it seems that even for instances like single-threaded applications, just adding threads would be the same as using async. For example:
#include <iostream> // std::cout
#include <future> // std::async, std::future
// a non-optimized way of checking for prime numbers:
bool is_prime (int x) {
std::cout << "Calculating. Please, wait...\n";
for (int i=2; i<x; ++i) if (x%i==0) return false;
return true;
}
int main ()
{
// call is_prime(313222313) asynchronously:
std::future<bool> fut = std::async (is_prime,313222313);
std::cout << "Checking whether 313222313 is prime.\n";
// ...
bool ret = fut.get(); // waits for is_prime to return
if (ret) std::cout << "It is prime!\n";
else std::cout << "It is not prime.\n";
return 0;
}
Why can't I just create a thread to call is_prime that writes to some variable, and then call join() before I print that variable? If I can do this, what really is the benefit of using async? Some specific examples would be very helpful.
This is not C++ specific, so I try to be a little bit generic. I'm sure there are C++ specific quirks as well.
Generally speaking, yes. You could just create a variable for the output, start a thread, give the address of the variable to the thread and later .join the thread and access the variable after the thread wrote to it. That works. Nothing wrong with it. We did that for many years.
But as the program gets more complicated, this gets more and more messy. More and more thread to keep running, more and more variables to keep in mind when and how to access them safely. Can I print i here, or do I need to .join a specific thread first? Who knows.
Futures (or Promises or Tasks) and async/await is a pattern many languages use nowadays under those or very similar names. They don't do anything we could not do before, but they make it a lot easier to maintain when the program grows and is no longer this one page example program that everybody can read on one screen.
Hello i'm newbie in C++ specially on STL,
I need to create a function with an infinite loop to calculate and process big data (such as Genetic Algorithm), but i also need keep Ui responsive and update it within (after each round) that infinite loop and start/stop operation manually.
something like this:
bool working = false;
void do_process()
{
while(working)
{
// do some stuff
}
}
void btnStart()
{
working = true;
do_process();
}
void btnEnd()
{
working = false;
}
would you please guide me to a proper solution without any 3rdparty lib, thanks.
and apologies for terrible English.
The code below should get you started. But be careful, implementing a multi-threading application is generally a hard problem also for experienced users. Lot of knowledge is required about memory access synchronization and deadlock analysis. Consider the example below is really essential. For instance, in btnStart and btnStop you should check if a thread is already running. Checking the global bool working may require synchronization. Similarly, checking for null pointer may require synchronization. Bottom line, it is way more complicate than it may seem.
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <memory>
bool working = false;
std::unique_ptr<std::thread> t;
void do_process()
{
while(working)
{
std::cout << "Hi. I am a secondary thread and I am running.\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void btnStart()
{
working = true;
t.reset(new std::thread(do_process)); // start the thread
}
void btnEnd()
{
working = false; // inform the thread of termination
t->join(); // wait for thread termination
t.reset(NULL);
}
int main()
{
std::cout << "Hi, I am the main thread.\n";
std::cout << "I'll now launch another thread and sleep for a while\n";
btnStart();
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
btnEnd();
std::cout << "What happened while I was slepping?\n";
return 0;
}
I am fairly new also to c++ but i have something that might help.
when i want to run something like an update to my code or to run something external without cramming my original project with code, i like to use ShellExecute to run another c++ program or external program. To use ShellExecute you need #include<windows.h>
For example if i want to update my program, i use #include<fstream>, #include<windows.h>, and #include<string> to check for a value in a file called 'updatereq.txt' (i make it my self). And in my program i run ifstream to check in the file if there is a '1'. If the if statement detects '1' it does this:
void Update(string filename)
{
ShellExecute(NULL,"open",filename.c_str(),NULL,NULL,SW_SHOWNORMAL)
}
This will run with:
HWND set as NULL, Operation set as: "open", File set as string:filenameconstant, Parameters set as NULL, Directory set as NULL(will run in the Directory of originally launching, usually at the main file), and Mode set as SW_SHOWNORMAL which will run it infront of you normally. This is also SW_SHOWMINIMIZED and SW_SHOWMAXIMIZED
Hope this helps!
PS: Remember to mention the file / program name that you are going to run when calling this function
I'm trying to create C++ program in the sense of embedded hardware programs that work in real time. The main loop in my C++ program uses a delay time of 250milliseconds. It's like:
int main()
{
do{
doSomething();
delay(250);
}while(1)
}
The delay in main loop is crucial for my program to operate.
I need to check something else using 5ms delays.
sideJob()
{
while(1){
checkSomething();
delay(5);
}
}
How do I define the function sideJob to run at the same with the main loop. All in all, I need to get the hang of threading by using, if possible, simple functions. I'm using Linux. Any help will be greately appreaciated.
EDIT: This is what I got so far, But I want to run the sideJob and main thread at the same time.
#include <string>
#include <iostream>
#include <thread>
using namespace std;
//The function we want to make the thread run.
void task1(string msg)
{
cout << "sideJob Running " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
//Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
while(1){
printf("Continuous Job\n");
}
}
Use different threads in order to do this tasks in parallel.
To learn for more about this, look here.
For an example on StackOverflow, look here.
You can also find plenty of tutorials out there (for example, here).
I am running two parallel threads. One of the threads need to have an asynchronous function call upon the fulfillment of a conditional statement. I have found out that std::async performs asynchronous function call using the launch policies, but I have a few questions regarding them.
Is there a policy to make it wait for a conditional statement to happen? According to what I have understood from this post, there are a variety of wait_for and wait_until functions, but I have found them to take in a time function, can these be suitably modified?
Will there be automatic destructor call at the end of the async function?
Will the function call affect the parent thread's functioning in any manner?
When you call std::async, you pass it the address of a function to call (along with any parameters you want to pass to that function).
It then creates a thread to execute that function asynchronously. It returns a future, which the parent thread can use to get the result from the child. Typical usage is something like this:
#include <string>
#include <future>
#include <iostream>
#include <chrono>
std::chrono::seconds sec(1);
int process() {
std::cerr << "Doing something slow\n";
std::this_thread::sleep_for(sec);
std::cerr << "done\n";
return 1;
}
int main(int argc, char **argv) {
if (argc > 1) {
auto func = std::async(process);
std::cerr << "doing something else that takes a while\n";
std::this_thread::sleep_for(sec);
func.get();
}
}
Note that we only have to use .get on the returned future to synchronize the threads. The sleep_for is just to simulate each thread doing something that takes at least a little while--if they finished too quickly, they wouldn't get a chance to really execute in parallel, since the first to run could finish and exit before the second got a chance to start running at all.
If you want to create explicit threads (i.e., create instances of std::thread), that's when you end up using std::wait_for and such (or can end up using them, anyway). With futures (i.e., what you create with std::async) you just use .get to wait for the thread to finish and retrieve whatever the thread function returned.
I want to call a function which will be asynchronous (I will give a callback when this task is done).
I want to do this in single thread.
This can be done portably with modern C++ or even with old C++ and some boost. Both boost and C++11 include sophisticated facilities to obtain asynchronous values from threads, but if all you want is a callback, just launch a thread and call it.
1998 C++/boost approach:
#include <iostream>
#include <string>
#include <boost/thread.hpp>
void callback(const std::string& data)
{
std::cout << "Callback called because: " << data << '\n';
}
void task(int time)
{
boost::this_thread::sleep(boost::posix_time::seconds(time));
callback("async task done");
}
int main()
{
boost::thread bt(task, 1);
std::cout << "async task launched\n";
boost::this_thread::sleep(boost::posix_time::seconds(5));
std::cout << "main done\n";
bt.join();
}
2011 C++ approach (using gcc 4.5.2, which needs this #define)
#define _GLIBCXX_USE_NANOSLEEP
#include <iostream>
#include <string>
#include <thread>
void callback(const std::string& data)
{
std::cout << "Callback called because: " << data << '\n';
}
void task(int time)
{
std::this_thread::sleep_for(std::chrono::seconds(time));
callback("async task done");
}
int main()
{
std::thread bt(task, 1);
std::cout << "async task launched\n";
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "main done\n";
bt.join();
}
As of C++11, plain c++ does have a concept of threads, but the most concise way to call a function asynchronously is to use the C++11 async command along with futures. This ends up looking a lot like the way you'd do the same thing in pthreads, but it's 100% portable to all OSes and platforms:
Say your function has a return value... int = MyFunc(int x, int y)
#include <future>
Just do:
// This function is called asynchronously
std::future<int> EventualValue = std::async(std::launch::async, MyFunc, x, y);
Catch? How do you know when it's done? (The barrier.)
Eventually, do:
int MyReturnValue = EventualValue.get(); // block until MyFunc is done
Note it's easy to do a parallel for loop this way - just create an array of futures.
You can't in plain C++. You'll need to use an OS-specific mechanism, and you need a point where execution is suspended in a way that allows the OS to execute the callback. E.g. for Windows, QueueUserAPC - the callback will be executed when you e.g. SleepEx or WaitForSingleObjectEx
The long answer involves implementing your own task scheduler and wrapping your "function" up into one or more tasks. I'm not sure you want the long answer. It certainly doesn't allow you to call something, completely forget about it, and then be notified when that thing is done; however if you are feeling ambitious, it will allow you to simulate coroutines on some level without reaching outside of standard C++.
The short answer is that this isn't possible. Use multiple threads or multiple processes. I can give you more specific information if you divulge what OS/platform you're developing for.
There are two bits to doing this.
Firstly, packing up the function call so that it can be executed later.
Secondly, scheduling it.
It is the scheduling which depends on other aspects of the implementation. If you know "when this task is done", then that's all you need - to go back and retrieve the "function call" and call it. So I am not sure this is necessarily a big problem.
The first part is then really about function objects, or even function pointers. The latter are the traditional callback mechanism from C.
For a FO, you might have:
class Callback
{
public:
virtual void callMe() = 0;
};
You derive from this and implement that as you see fit for your specific problem. The asyncronous event queue is then nothing more than a list<> of callbacks:
std::list<Callback*> asyncQ; // Or shared_ptr or whatever.
I'm not sure I understand what you want, but if it's how to make use of a callback: It works by defining a function pointer, like this (untested):
// Define callback signature.
typedef void (*DoneCallback) (int reason, char *explanation);
// A method that takes a callback as argument.
void doSomeWorkWithCallback(DoneCallback done)
{
...
if (done) {
done(1, "Finished");
}
}
//////
// A callback
void myCallback(int reason, char *explanation)
{
printf("Callback called with reason %d: %s", reason, explanation);
}
/////
// Put them together
doSomeWortkWithCallback(myCallback);
As others have said, you technically can't in plain C++.
However, you can create a manager that takes your task and does time-slicing or time scheduling; with each function call, the manager uses a timer to measure the amount of time the process took; if the process took less time than scheduled, and it thinks it can finish another call and use up the remaining time without going over, it can call it again; if the function does go over the alloted time, it means the function has less time next update to run. So, this will involve creating a somewhat complex system to handle it for you.
Or, if you have a specific platform in mind, you could use threading, or create another process to handle the work.