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*>
Related
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)
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();
}
}
I always saw in the internet the rule:
If you don't detach\join a thread, then abort will be called.
I need a reason for why that abort happens.
I can understand with join — because when not doing join to some thread, the the main can be closed before the thread and it can make problems.
But detach doesn't do anything! It has no purpose (at least from what I've seen when running a thread with or without being detached).
What exactly make the abort to jump, any what exactly is the purpose of detach?
Here is a simple example for what causing "aborting":
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
void pause_thread(int n)
{
std::this_thread::sleep_for (std::chrono::seconds(n));
std::cout << "pause of " << n << " seconds ended\n";
}
int main()
{
std::cout << "Spawning and detaching 3 threads...\n";
std::thread (pause_thread,1);
std::cout << "Done spawning threads.\n";
// give the detached threads time to finish (but not guaranteed!):
pause_thread(5);
return 0;
}
A thread is a different beast from a process. Threads are not in a parent/child relation at all.
C++11 thread implementation has to be compatible with all major OS threads, so it had to make design decisions, which cannot be understood at first sight.
I'll describe pthread, which is used in the linux world.
When you create a thread, you can specify its detachstate. It can be two values:
DETACHED: when the thread exits, its allocated resources automatically released. Thread cannot be joined.
JOINABLE: when the thread exits, some of its resources are not automatically freed. For example, its return code (in pthread, there is a return value of a thread). Thread can be joined. Resources will be freed at join().
C++ threads are created as JOINABLE, but you can detach it later.
Now, if you don't detach/join a thread, at ~thread(), what could a thread implementation do? It is an issue, because if it doesn't do anything, then some resource will be silently leaked (as a JOINABLE thread when exits, some of its resources are not automatically freed)
call join() automatically: not a good idea, as the program can stall on it (if the thread still runs). It is potentially a programming bug.
call detach() automatically: not a good idea either, as it could be a programming bug (thread continue to run, but its thread object is destroyed - a programmer should explicitly call detach() in this case)
call abort(): this is the best that an implementation can do, to avoid programming errors
So the designers of std::thread chose to call abort() to avoid programming errors.
(On windows, the thread system is similar. You have to call CloseHandle for a thread so its resources can be released)
In a tutorial I am following, the author wrote a program that showed that the destructors of std::futures don't always execute the task. In the following program, 10 threads created with std::async() are moved into the vector, and then we wait for their destructors to run.
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
int main()
{
std::cout << "Main thread id: " << std::this_thread::get_id() << std::endl;
std::vector<std::future<void>> futures;
for (int i = 0; i < 10; ++i)
{
auto fut = std::async([i]
{
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << std::this_thread::get_id() << " ";
});
futures.push_back(std::move(fut));
}
}
The result is machine-dependent, but what we found was that only 6 threads were launched when the destructors ran (we only got 6 ids printed after the main thread id output). This meant that the other four were deferred, and deferred threads don't run during std::future's destructors.
My question is why were some threads forced to execute while others were deferred. What is the point of deferring them if the life of the std::future is ending?
the author wrote a program that showed that the destructors of std::futures don't always execute the task.
The destructors never execute the task. If the task is already executing in another thread the destructor waits for it to finish, but it does not execute it.
what we found was that only 6 threads were launched when the destructors ran
This is incorrect, the threads are not launched when the destructors run, they are launched when you call std::async (or some time after that) and they are still running when the destructors start, so the destructors must wait for them.
What is the point of deferring them if the life of the std::future is ending?
Again, they are not deferred when the destructor runs, they are deferred when std::async is called, they are still deferred when the destructor runs, and so they just get thrown away without being run, and the destructor doesn't have to wait for anything.
I don't know if you're quoting the tutorial and the author of that is confused, or if you're confused, but your description of what happens is misleading.
Each time you call std::async without a launch policy argument the C++ runtime decides whether to create a new thread or whether to defer the function (so it can be run later). If the system is busy the runtime might decide to defer the function because launching another thread would make the system even slower.
Your async() calls use the default launch policy, which is launch::async|launch::deferred meaning that "The function chooses the policy automatically (at some point). This depends on the system and library implementation, which generally optimizes for the current availability of concurrency in the system."
thread::hardware_concurrency may give you hints about maximum hardware concurrency on your system. This can contribute to explain why some threads are necessarily deferred (especially if your loop is grater than the hardware concurrency) or not. However, beware that other running processes might use the hardware concurrency as well.
Please note as well that your asynchronous threads make use of cout which could delay some of them due to synchronization (more here)
I heard that "a modern operating system will clean up all threads created by the process on closing it" but when I return main(), I'm getting these errors:
1) This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
2) terminate called without an active exception
My implementation looks like this (I'm writing now for example sorry for bad implementation):
void process(int id)
{
while(true) { std::this_thread::sleep_for(std::chrono::milliseconds(1); } }
}
int main()
{
std::thread thr1(process, 0);
std::thread thr2(process, 1);
//thr1.detach();
//thr2.detach();
return 0;
}
If I uncomment detach();s, there is no problem but my processing threads will be socket readers/writers and they will run infinitely (until main returns). So how to deal with it? What's wrong?
EDIT: Namely, I can't detach() every thread one-by-one because they will not be terminated normally (until the end). Oh and again, if I close my program from the DDOS window's X button, (my simple solution not works in this case) my detach(); functions being passed because program force-terminated and here is the error again :)
What happens in an application is not related to what the OS may do.
If a std::thread is destroyed, still having a joinable thread, the application calls std::terminate and that's what is showing up: http://en.cppreference.com/w/cpp/thread/thread/~thread`
With the c++11 threads, either you detach if you do not care on their completion time, or you care and need to join before the thread object is destroyed.