I am beginner in c++. I have just started learning c++. I would like to ask that is it possible to write non blocking programming in c++ in easy way. How i mention up, I do not understand very complicate code yet. I Intend Something like this
do {
//do stuff
sleep(5);
i++;
} while(i != 1000);
cout << "Enter the value : ";
cin >> inputvale;
While do {} while(); loop is looping and same time i want to use cout and cin.
Question: Is there any way to do this ?
You have some options to do asynchronous programming in C++.
C++ runtime offers you (E.g. Threads)In general you have one main Thread, that is executing, what is defined in the main function (The entrypoint of your programm).
In the demonstration example, another such Thread will be spawned, which is executing code, that is defined in a separate function (foo), in parallel to the main thread. You dont know when this thread does its work nor when it is finished. It depends on the thread sheduling mechanism (Thats another topic)...
...However you can query the status of threads, receive callbacks, when they are finished (Asyncronous programming) or do a blocking wait until they are finished (Syncronous programming). Both methods can get very complex and you may run into synchronization problems...
... This is why the usage of libraries is often recommended when it comes to parallel programming. One good and platform independent library is Boost. You basically can do the very same as with Threads but in a more defined way, which is less error prone. Tutorial
In contrast custom implementations with low level mechanisms like Threads offer the benefit of more granularity and is the way to go for more individual solutions.
I would recommend you to do some quick tutorials on both. One easy to follow link for Boost is above and the entry point for Thread programming is my example listed below.
#include <iostream>
#include <thread>
using namespace std;
// Read one character from the commandline:
void foo()
{
// Variable holding the character
char inputValue;
cout << "Enter the value : ";
cin >> inputValue;
}
int main() {
// Spawn new thread that calls foo()
thread fooThread(foo);
// This is your main loop:
int i = 0;
do {
//do stuff
i++;
} while (i != 1000);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With