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
Related
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.
This is my first question on stackoverflow and I'm new to C++. I hope you can all forgive my ignorance to the probably obvious problem here, but I'm at a loss.
Basically, I'm just trying to catch events emitted by a nodejs server in my C++ client. I've successfully compiled my binary (imported boost and socketio) and much hardache. I'm trying to emit an event through a websocket connection, but I first need to ensure the connection is successful. I've been mostly following the tutorial at this link: https://socket.io/blog/socket-io-cpp/. I've also been following the source code, which can be found here: https://github.com/socketio/socket.io-client-cpp/tree/master/examples/QT
For some reason, I seem to be getting a segfault when I access my _io pointer in my bound function (in the onConnected function of the SocketHandler class).
I'm sure I'm doing something silly, but any help is appreciated. Maybe I'm misunderstanding the use of the std::bind function? I'm coming from a mostly javascript world.
main.cpp
#include "sockethandler.h"
int main()
{
SocketHandler sh;
}
sockethandler.cpp
#include <iostream>
#include "sockethandler.h"
const char name[13] = "raspberry_pi";
SocketHandler::SocketHandler() :
_io(new client())
{
using std::placeholders::_1;
_io->set_socket_open_listener(std::bind(&SocketHandler::OnConnected,this,_1));
_io->connect("http://127.0.0.1:3000");
_io->socket()->on("bot-command", [&](sio::event& ev) {
std::cout << "GOT IT!" << "\n";
//handle login message
//post to UI thread if any UI updating.
});
}
void SocketHandler::OnConnected(std::string const& nsp)
{
std::cout << "CONNECTED" << "\n";
// I can access a private class variable such as _a as a string
// here
_io->socket()->emit("join");
}
sockethandler.h
#ifndef SOCKETHANDLER_H
#define SOCKETHANDLER_H
#include <sio_client.h>
using namespace sio;
class SocketHandler {
public:
explicit SocketHandler();
private:
void OnConnected(std::string const& nsp);
std::unique_ptr<client> _io;
};
#endif // SOCKETHANDLER_H
Pretty sure the socket io library you are using is threaded. Your object is created, sets up the callback (which include references to itself), the constructor exits, main exits and the automatic (stack) variable sh is destroyed. Then the socket io library tries to run the callback which no longer has references to a valid object and it crashes. Put a debug statement in your SocketHandler destructor like cerr << "destructor called" << endl; and I'm pretty sure you'll always see that called before the program crashes.
To prove it to yourself, put a sleep(10); or whatever as the last line of code in your main to stall it from exiting and I'm guessing you'll see your program succeed.
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 not an experinced c++ programmer. So I just want to know how to implement timer and timertask just like java has in C++. I have tried timer_create example that is in man page of timer_create but It is not working as per my requirement.
I want that after particualar time span an event should fire, and if specific condition fulfills then timer should be canceled.
Any help would be highly appreciated.
Thanks,
Yuvi.
I too was looking for a Java like TimerTask but I needed one for Windows C++ when I came across this question. After a day of researching mostly on SO and learning about passing class member functions, I was able to put together a solution that seems to work well for me. I realize that I am years late in answering this question but maybe someone still looking for this solution will find this useful.
This is a Windows only solution which I tested on Windows 10 using Visual Studio C++. I'm still learning C++ so please be gentle if I've broken any rules. I realize the exceptions are elementary but they are easy to customize to your needs. I created a TimerTask class similar to the Java class. You'll need to derive a new user class from the TimerTask class and create a "task" function that includes the code you want executed at regular intervals. Here is the TimerTask class:
--TimerTask.h--
#pragma once
#include <thread>
class TimerTask {
HANDLE timeoutEvent;
DWORD msTimeout;
bool exit = false;
void* pObj;
static void taskWrapper(TimerTask* pObj) {
while (!pObj->exit) {
DWORD waitResult = WaitForSingleObject(pObj->timeoutEvent, pObj->msTimeout);
if (pObj->exit)
break;
pObj->task();
}
}
public:
TimerTask::TimerTask() {
timeoutEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!timeoutEvent) {
throw "TimerTask CreateEvent Error: ";
}
}
TimerTask::~TimerTask() {
CloseHandle(timeoutEvent);
}
// Derived class must create task function that runs at every timer interval.
virtual void task() = 0;
void start(void* pObj, DWORD msTimeout) {
this->pObj = pObj;
this->msTimeout = msTimeout;
std::thread timerThread(taskWrapper, (TimerTask*)pObj);
timerThread.detach();
}
void stop() {
exit = true;
if (!SetEvent(timeoutEvent))
throw "TimerTask:stop(): Error: ";
}
};
And here is a sample of usage. For brevity I didn't include error checking.
--Test.cpp--
#include "Windows.h"
#include <iostream>
#include "TimerTask.h"
using namespace std;
class KeepAliveTask : public TimerTask {
public:
void task() {
cout << "Insert your code here!\n";
}
};
int main()
{
cout << "Hello, TimerTask!\n";
KeepAliveTask keepAlive;
keepAlive.start(&keepAlive, 1000); // Execute once per second
Sleep(5100); // Pause 5.1s to give time for task thread to run.
keepAlive.stop();
Sleep(1000); // Pause another sec to give time for thread to stop.
return 0;
}
This is generally a very difficult question, since you are inherently asking for some concurrent, or at least asynchronous processing.
The simplest, single-threaded solution is to use something like Posix's alarm(2). This will cause a signal to be sent to your process after a specified time. You need to register a signal handler (e.g. with signal(2)), but you are subject to all its limitations (e.g. you must only call async-safe functions within the handler).
A second, single-threaded option is to use a select-style (or epoll-style) I/O loop and use a kernel timer file descriptor. This is a very recent Linux feature, though, so availability will vary.
Finally, the typical, general solution is to use multiple threads: Make a dedicated thread for the timer whose only purpose is to sleep for the set time span and then execute some code. For this you will have to bear the full weight of concurrent programming responsibilities, such as handling shared data, guaranteeing the absence of races, etc.
Some higher-level libraries like Boost.ASIO and the new standard library provide some nice timing mechanisms once you've decided to go down the multithreaded route.
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.