Limit function execution time - c++

Is there any way to make a function execute it's code for a specific time, then pause it's execution and move on to another function. I want to be able to make a program that can multitask. I have already tried using <thread>, but whenever I try to run the program it runs one of the threads partially and then the debugger throws a "signal SIGABRT" and stops. Is there any other way of doing this?
Edit:
Here is the code I tried using the threads with. I made this as a test in order to try to get the two functions going at the same time, then add the timer to pause the execution. I want it to be able to run one thread for a short time, then move onto another thread, and to keep on doing this.
#include <iostream>
#include <thread>
using namespace std;
void task1()
{
for (int i=0; i<100; i++)
{
cout << i << '\n';
}
}
void task2()
{
for (int i=0; i<100; i++)
{
cout << i << '\n';
}
}
int main()
{
thread t1(task1);
thread t2(task2);
return 0;
}

The most commonly used way of doing this without multi-threading is to abuse the message loop in used by most GUI frameworks. A bit of work is done in a for loop and then PumpMessages or whatever is called to keep to GUI responsive by processing queued messages and then some more work is done.
In my opinion this is a bad practice. What it actually results in is inconsistent, slow and unresponsive applications.
The other option would be resumable functions such as those available in C# and proposed for C++17. However these are not going to be readily available at the moment.
Getting multi-threading right is hard, as you have already discovered crashes and synchronisation bugs are common and can only be found at run time. However multi-core CPUs are the standard everywhere now and you can't really avoid multi-threading so it is best to learn how to get it right.

Related

How to implement Priority Preemptive Scheduling (similar to interrupts) with threads in C++

I want to write a C++ program on Windows (but preferably to support cross-platform) in which I have two threads that are scheduled based on Priority Preemptive Scheduling - which is like an interrupt behavior (when the interrupt occurs, the main thread pauses wherever it is and only when the interrupt thread goes back to sleep the main thread will resume from where it was paused).
These are the threads:
Thread T_main
Thread T_interrupt.
T_main runs all the time in a while loop.
T_interrupt is supposed to be executed once every second and it does something very quick.
The code in T_main is rather large (thousands of lines of code).
It must be extremely time accurate.
I want that when the time comes for the T_interrupt thread to run, it will be prioritized so that it will run without interruption until it finishes and only then the thread T_main will resume from where it paused.
If you are wondering what I am trying to do then here is a basic explanation:
Basically, I am running a simulation of my embedded project. I mocked my entire hardware and I want to run my application on a simulator on the PC. The purpose is to test the logic implementation of my application. Compiler differences and other imperfections are taken into consideration. What is critical for me is to be able to simulate a 1-second tick timer based interrupt that exists on my MCU. I am finding it difficult to simulate this behavior as thread scheduling seems to be cooperative and not preemptive.
I tried using priorities and setting scheduling methods such as Round Robin SCHED_RR or FIFO SCHED_FIFO but in all cases the scheduling implementation is still cooperative and not preemptive.
Here is my code:
#include <iostream>
#include <thread>
#include <pthread.h>
#include <string>
using namespace std;
void MainApplicationFunc(void)
{
// Infinite loop in which the app is running
while(1)
{
MainProgram();
}
}
void TickTimerInterruptFunc()
{
while(1)
{
TickTimer();
std::this_thread::sleep_for(1s);
}
}
void setScheduling(std::thread &th, int policy, int priority)
{
sched_param sch_params;
sch_params.sched_priority = priority;
if(pthread_setschedparam(th.native_handle(), policy, &sch_params))
{
std::cerr << "Failed to set Thread scheduling" << std::endl;
}
}
int main()
{
std::thread T_interrupt(TickTimerInterruptFunc);
setScheduling(T_interrupt, SCHED_FIFO, 1);
std::thread T_main(MainApplicationFunc);
setScheduling(T_main, SCHED_FIFO, 20);
T_main.join();
T_interrupt.join();
}
I found several solutions for this issue and I thought I'd share them here for everybody else. Throughout stackoverflow I found others who asked similar questions to this one and there are several possible solutions.
Possible Solutions to Implement interrupt behavior with threads:
Force a context switch on your thread. I found some useful reference to how to do this on Windows as depicted in FreeRTOS Windows Simulator. For me personally, this seems to be the best option. Moreover, I might just use this simulator instead of building my own.
Write a windows driver as mentioned here: https://stackoverflow.com/a/13819216/4441211
Use SuspendThread and ResumeThread. Although when using this method you should be aware that they are async in nature as depicted here so this is not ideal.

Force program termination if threads block in C++

When a class is responsible for managing a thread, it is a common pattern (see for example here) to join this thread in the destructor after you have made sure that the thread will finish in time. However, this is not always trivial as outlined in the linked thread leading to a program that never terminates if done incorrectly. Given below is an example to reproduce such a situation:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
class Foo {
public:
Foo() {
mythread = std::thread([&](){
int i = 0;
while(running) {
std::cout << "hi" << std::endl;
if (i++ >= 2) {
// placeholder for e.g. a blocking condition variable
std::this_thread::sleep_for(1000h);
}
std::this_thread::sleep_for(500ms);
}
});
}
~Foo() {
running = false;
mythread.join();
}
private:
std::thread mythread;
bool running{true};
};
int main() {
Foo bar;
std::this_thread::sleep_for(1s);
// enabling this line will block the termination
//std::this_thread::sleep_for(2s);
std::cout << "ending" << std::endl;
}
What I am searching for is a solution that forcefully terminates the program if this situation occurs. Of course, one should always strive towards finishing the thread properly, but having such feature would be good as last resort to have a peace of mind, especially for unobserved embedded systems where crashing programs can be easier restored and debugged than blocking programs.
A rough solution draft would be to start a thread at the end of the main that sleeps for a few seconds and if the program has not ended after that time, std::terminate is called (and ideally a corresponding error is reported). However, we have a chicken-or-egg problem because this new thread will of course keep the program from ending in time. I would highly appreciate any ideas.
EDIT: The solution should not require modification of the Foo class itself so that it also covers respective bugs in unmodified code of e.g. external libraries. Ideally, it would even cover threads no class feels responsible for ending them before the main ends (classes with static storage duration or even no longer referenced objects with dynamic storage duration), but that might not be possible at all without in-depth OS hacking or an external process monitor.
There are several solutions:
Investigate and fix the root problem (this is the best and correct solution)
Workarounds:
You can notify from thread about exiting via condition variable. And only after it do join. If CV's wait_for returns with timeout - kill thread (bad solution, there are another problems).
You can create watch-thread, which will verify time-counter. Counter should be reset from time to time by the application. If watch-thread detects too high value in time-counter, it restarts whole the application.
Move suspicious code out of your application to separate process and communicate with it via IPC. In case of problems - restart that application (best among the workarounds)

How to manage multiple threads without making the user wait?

Sorry if this was worded poorly, I wasn't sure how to give an accurate description of what I wanted in the title. But basically my goal is to have the user input times and for the program to alert them when the time has passed. After the time has passed, the program looks for another time while allowing the user to input more times. Basically, it would look something like this:
void printTime(tm time) {
//sleep until time
cout << "it is " << time << endl;
lookForNextTime();
}
void lookForNextTime() {
//find earliest time
printTime(time);
}
int main() {
//create thread in lookForNextTime
while(true) {
//ask user to insert more times until they quit
}
}
So while the user is inserting more times, the other thread is waiting to print out the earliest scheduled time. If the user inputs a new time that is after the current scheduled time, there shouldn't be an issue. But what happens if they input a time that is meant to come before the next time?
This is the problem. Let's say the earliest scheduled time is a month from now. The user inputs a new time that is two weeks from now. So what do we do? Make another thread, I guess. But then the user wants to input a time next week. And then a time three days from now. And then a time tomorrow. And so on.
I'm new to multithreading, but surely it's not a good idea to just let all of these new threads be made without regulation, right? So how do we control it? And when it's time to remove a thread, we need to use .join, correct? Is there a way to implement join that doesn't require the user to wait for the time to pass and allows them to continue inputting more times without interruption?
Welcome to StackOverflow. I am fairly new to threading in C++ myself so I'm not familiar with the best libraries and techniques, but I can share at least a little about the basics I do know, and hopefully that gives you a feel of where to go from there.
If I understand correctly I believe you question mainly revolves around join() so I'll start there.
Calling join() is how you wait for a thread to join before moving on, but you don't have to do that as soon as you create one or it would be pretty pointless. You can let the thread go on its own merry way and it will end when it is done without any further input from the main thread (please correct me I am mistaken).
The important thing about join() is that you call it on all the threads to wait for them before exiting the program (or otherwise aborting them somehow, safely of course). Otherwise they will continue running even after main() returns and will cause issues when they try to access memory as they are no longer attached to a running process. Another potential use might be to have a few worker threads match up at certain checkpoints in a calculation to share results before grabbing the next chunk of work.
Hope that helps. I had a few more thoughts though that I thought I would share in case you or some future reader aren't familiar with some of the other concepts involved in this example.
You don't indicate whether you have an way in mind for keeping tracking of the times and sharing them between threads, so so I'll just throw out a quick tip:
Lock your buffer before you add or pop from it.
Doing so is important in order to avoid race conditions where one thread could be trying to pop something off while the other is adding and causing weird issues to arise, especially if you end up using something like set from the standard library which sorts and ensures you only have one copy of any given element upon insertion.
If you aren't familiar with locking mechanisms then you could find examples of using Mutexes and Semaphores in C++, or do a search for 'locking' or 'Synchronization Objects'. You may consider the humble Mutex from the standard library.
As far as actually creating the threads, a couple things come to mind. One thought is using thread pools. There are several libraries out there for handling threading pools, with one such example being Apple's open source Grand Central Dispatch (commonly known as libdispatch) which can be used on Linux for sure, but for Windows you would want to look up something else (I'm not that familiar with the Windows platform unfortunately). They manage the life cycles of the threads you are and are not using so they could potentially help. Again, being a bit new to this myself I'm not 100% sure that would be the best thing for you, especially since you have other parts of the project to work out still, but it may be worth looking in to.
Even without using thread pools (say you use pthreads) I don't think you need to worry too much about starting a bunch of threads on your own as long as you put some reasonable limit on it (how much is reasonable I'm not sure but if you check out Activity Monitor in macOS or Task Manager in Windows or TOP in Linux you will see that at any given time many programs on your machine may be rocking quite a few threads-right now I have 5090 threads running and 327 processes. That's about 15.5 threads per process. Some process go much higher than that).
Hope something in there helps.
Here is an example from what I understood you're trying to do using the standard library. Usually threading will be controlled through various std::mutex, std::conditional_variable, and related flags to achieve the desired affect. There are libraries that can simplify threading for more complex scenarios, most prominently boost::asio.
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <condition_variable>
#include <mutex>
bool spuriousWakeup = true;
bool timerSet = false;
bool terminated = false;
int timerSeconds = 0;
std::thread timerThread;
std::mutex timerMutex;
std::condition_variable timerWakeup;
void printTimeThreadFunc()
{
// thread spends most of the time sleeping from condition variable
while (!terminated){
std::unique_lock<std::mutex> lock(timerMutex);
if(timerSet){
// use condition variable to sleep for time, or wake up if new time is needed
if(timerWakeup.wait_for(lock, std::chrono::seconds(timerSeconds), []{return !spuriousWakeup;})){
std::cout << "setting new timer for " << timerSeconds << " seconds!" << std::endl;
}
else{
std::cout << "timer expired!" << std::endl;
// timer expired and there is no time to wait for
// so next time through we want to get the un-timed wait
// to wait indefinitely for a new time
timerSet = false;
}
}
else{
std::cout << "waiting for timer to be set!" << std::endl;
timerWakeup.wait(lock, []{return !spuriousWakeup;});
}
spuriousWakeup = true;
}
}
int main()
{
// timer thread will exist during program execution, and will
// be communicated with through mutex, condition variable, and flags.
timerThread = std::thread(printTimeThreadFunc);
while (!terminated){
// get input from user
std::string line;
std::getline(std::cin, line);
// provide a way to quit
if (line == "end") {
terminated = true;
break;
}
// make sure its a number
try{
// put scope on lock while we update variables
{
std::unique_lock<std::mutex> lock(timerMutex);
timerSet = true;
timerSeconds = std::stoi(line);
spuriousWakeup = false;
}
// let thread know to process new time
timerWakeup.notify_one();
}
catch (const std::invalid_argument& ia) {
std::cerr << "Not a integer" << ia.what() << '\n';
}
}
// clean up thread
if(terminated && timerThread.joinable()){
timerWakeup.notify_one();
timerThread.join();
}
}

Multithreaded C++ Program Not Running In Parallel Using vector<thread> and .join()

Note: This is the first post I have made on this site, but I have searched extensively and was not able to find a solution to my problem.
I have written a program which essentially tests all permutations of a vector of numbers to find an optimal sequence as defined by me. Of course, computing permutations of numbers is very time consuming even for small inputs, so I am trying to speed things up by using multithreading.
Here is a small sample which replicates the problem:
class TaskObject {
public:
void operator()() {
recursiveFunc();
}
private:
Solution *bestSolution; //Shared by every TaskObject, but can only be accessed by one at a time
void recursiveFunc() {
if (base_case) {
//Only part where shared object is accessed
//base_case is rarely reached
return;
}
recursiveFunc();
}
};
void runSolutionWithThreads() {
vector<thread> threads(std::thread::hardware_concurrency());
vector<TaskObject> tasks_vector(std::thread::hardware_concurrency());
updateTasks(); //Sets parameters that intialize the first call to recursiveFunc
for (int q = 0; q < (int)tasks_vector.size(); ++q) {
threads[q] = std::thread(tasks_vector[q]);
}
for (int i = 0; i < (int)threads.size(); ++i) {
threads[i].join();
}
}
I imagined that this would enable all threads to run in parallel, but I can see using the performance profiler in visual studio and in the advanced settings of windows task manager that only 1 thread is running at a time. On a system with access to 4 threads, the CPU gets bounded at 25%. I get correct output every time I run, so there are no issues with the algorithm logic. Work is spread out as evenly as possible among all task objects. Collisions with shared data rarely occur. Program implementation with thread pool always ran at nearly 100%.
The objects submitted to the threads don't print to cout and all have their own copies of the data required to perform their work except for one shared object they all reference by pointer.
private:
Solution* bestSolution;
This shared data is not susceptible to a data race condition since I used lock_guard from mutex to make it so only one thread can update bestSolution at a time.
In other words, why isn't my CPU running at nearly 100% for my multithreaded program which uses as many threads as there are available in the system?
I can readily update this post with more information if needed.
In debugging your application, use the debugger to "break all" threads. Then examine each thread with the debug thread window to see where each thread is executing. Likely you will find that only one thread is executing code, while the rest are all blocked on the mutex that the one running thread is holding.
If you show a more complete example of the code it can greatly assist.

Run threads in parallel in C++ [duplicate]

This question already has answers here:
std::thread - "terminate called without an active exception", don't want to 'join' it
(3 answers)
Closed 9 years ago.
I am trying to do a dekker algorithm implementation for homework, I understand the concept but I'm not being able to execute two threads in parallel using C++0x.
#include <thread>
#include <iostream>
using namespace std;
class Homework2 {
public:
void run() {
try {
thread c1(&Homework2::output_one, this);
thread c2(&Homework2::output_two, this);
} catch(int e) {
cout << e << endl;
}
}
void output_one() {
//cout << "output one" << endl;
}
void output_two() {
//cout << "output two" << endl;
}
};
int main() {
try {
Homework2 p2;
p2.run();
} catch(int e) {
cout << e << endl;
}
return 0;
}
My problem is that the threads will return this error:
terminate called without an active exception
Aborted
The only way to success until now for me has been adding c1.join(); c2.join(); or .detach();
the problem is that join(); will wait for the threads to finish, and detach(); ... well Im not sure what detach does because there is no error but also no output, I guess it leaves the threads on their own...
So all this to say:
Does anybody knows how can I do this both threads to run parallel and not sequencial??
The help is must appreciated!
Thanks.-
P.S:
here is what I do for build:
g++ -o output/Practica2.out main.cpp -pthread -std=c++11
The only way to success until now for me has been adding c1.join(); c2.join(); or .detach();...
After you have spawned the 2 threads, your main thread continues on and, based on your code, ends 'pretty' quick (p2.run() then return 0; are relatively close in CPU instruction 'time'). Depending on how quickly the threads started, they might not have had enough CPU time to fully 'spawn' before the program terminated or if they did fully spawn, there might not have been enough time to do the proper cleanup by the kernel. This is also known as a race condition.
Calling join on the spawned threads from the thread you spawned them from allows the threads to finish and clean up properly (under the hood) before your program exits (a good thing). Calling detach works in this scenario too as it releases all resources (under the hood) from your thread object, but keeps the thread active. In the case of calling detach there were no errors reported because the thread objects were detached from the executing threads, so when your program exited, the kernel (nicely) cleaned up the threads for you (or at least that's what might happen, depends on OS/compiler implementation, etc.) so you didn't see your threads ending 'uncleanly'.
So all this to say: Does anybody knows how can I do this both threads to run parallel and not sequencial??
I think you might have some confusion on how threads work. Your threads already run in 'parallel' (so to speak), that is the nature of a thread. Your code posted does not have anything that would be 'parallel' in nature (i.e. parallel computing of data) but your threads are running concurrently (at the same time, or 'parallel' to each).
If you want your main thread to continue without putting the join in the run function, that would require a little more code than what you currently have and I don't want to assume how your code's future should look, but you could take a look at these two questions regarding the std::thread as a member of a class (and executing within such).
I hope that can help.
Ok this is bit more complex but I will try to explain some things in your code.
When you create the threads in the method called run, you want to print two things (imagine you uncomment the lines), but the thread object is destroyed in the stack unwiding of the method which created them (run).
You actually need to do two things, first create the threads and keep them running(for example do it as pointers) and second call the method join to release all the memory and stuff they needed when they are finished.
You can store you threads in a vector something like std::vector<std::thread*>