Code crashes when creating new thread c++ - c++

I'm new to C++ and I'm trying to make the console print "after 5 seconds" after 5000 ms. Then print "insta log" immediately after the new thread's declaration.
But doing so crashes with the following error:
"Debug Error!
[PROGRAM PATH]
abort() has been called
"
This is my code:
#include <iostream>
#include <thread>
#include <Windows.h>
#include <ctime>
using namespace std;
void f() {
Sleep(5000);
cout << "after 5 seconds" << endl;
}
int main() {
cout << "starting" << endl;
// Pass f and its parameters to thread
// object constructor as
thread t(&f);
cout << "insta log" << endl;
}
I'm unsure why this is happening. I've searched around and I found a "fix" but it makes my code not behave as intended.
This is the "fix"
#include <iostream>
#include <thread>
#include <Windows.h>
#include <ctime>
using namespace std;
void f() {
Sleep(5000);
cout << "after 5 seconds" << endl;
}
int main() {
cout << "starting" << endl;
// Pass f and its parameters to thread
// object constructor as
thread t(&f);
t.join();
cout << "insta log" << endl; // doesn't print for 5 seconds
}
This removes the error message but yields the main thread for 5 seconds. Which makes my code not work as intended.
Thanks in advance, any help is appreciated!

This removes the error message.
Yes.
but yields the main thread for 5 seconds.
This is not what is happening!
The main thread is waiting for your second thread t to finish (slightly different to yielding).
The problem before was that the main thread was exiting the application (and you are not allowed to have other threads running after the main thread exits (this is because what happens to the children thread is highly depended on the threading implementation and they very wildly).
In the C++ std::thread class they try and compensate for the above behavior by making the destructor terminate() if the current thread leaves scope without the child thread of execution completing.
This means you usually have to call the join() method to wait for the child to exit.
So what you usually do is 1: create a std::thread object that does some work in the background 2: while you do some work locally. Then when you have finished, 3: you call join() and wait for the child object to also finish (if it has already finished this does nothing). Then you can exit scope (and exit the main).
Which makes my code not work as intended.
int main()
{
// STUFF.
// Create your thread.
thread t(&f);
// Print any thing you want.
// i.e. do the work you want to do in main.
cout << "insta log" << endl;
// When you have finished.
// wait for the child to finish.
t.join();
} // now the std::thread::~thread check to make sure the
// child thread of execution is no longer running.

If you had clicked 'retry' in that dialog you would have seen why your code died. Its right here
~thread() noexcept {
if (joinable()) {
_STD terminate();
}
}
in the MSVC implementation of std::thread. The code says that destroying a thread thats still joinable (ie is running) is illegal. I dont know if thats c++ defined behavior, a quick search didnt show me. Anyway when you join the thread, you will wait till its OK to destroy it

Functions are already passed around as pointers, use thread t(f) instead of thread t(&f).
Moreover, since your main() neither lasts longer than the thread or calls a t.join(), the program will end before the thread finishes it's code, so that might be another reason for a crash. In fact it is probably the reason for the crash.
If you want "insta log" to print instantly, then call t.join() at the end of main(). t.join() will wait for the thread t to end before continuing.

Related

My code is exiting with use-after-free error but I don't know why?

I'm a multithreading beginner and I'm wring the below code:
#include <iostream>
#include <functional>
#include <thread>
#include <mutex>
#include <future>
#include <unistd.h>
using namespace std;
class Foo {
public:
Foo() {}
~Foo() { cout << "foo dtor" << endl; }
void first(function<void()> printFirst) {
printFirst();
}
void second(function<void()> printSecond) {
printSecond();
}
void third(function<void()> printThird) {
printThird();
}
};
int main() {
Foo foo;
thread t1([&foo] {
function<void()> print11 = [] { cout << "1" << endl; };
foo.first(print11);
});
thread t2([&foo] {
function<void()> print21 = [] { cout << "2" << endl; };
foo.second(print21);
});
thread t3([&foo] {
function<void()> print31 = [] { cout << "3" << endl; };
foo.third(print31);
});
sleep(2);
// t1.join();
// t2.join();
// t3.join();
return 0;
}
And I'm getting the error
"Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
If I uncomment the three join() lines, the program exit normally.
I have a feeling that the error is due to use after free, but cannot explain why. What I'm thinking is the main thread will sleep 2 seconds before it really finishes, and during the main thread is sleeping, the t1, t2, t3 should already finish. Hence, even if foo is destroyed, the three thread won't use it after 2 seconds. As far as I understand, it should not have use after free problem. Could anybody explain? Thanks!
This does not look to me like a use after free problem, and it's not a race condition either. It's required behavior. Attempting to destroy a thread object that is in a joinable state (which yours would be under the circumstances) is required to terminate the program (N4835, §[thread.thread.destr]/1):
~thread();
If joinable(), calls terminate(). Otherwise, has no effects. [Note: Either implicitly detaching or
joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach)
or performance (for join) bugs encountered only when an exception is thrown. Thus the programmer
must ensure that the destructor is never executed while the thread is still joinable. —end note]
A thread is joinable() from the time it starts to run until the time it is join()ed or detach()ed.
Summary
Destroying a thread must abort the program if the thread is in a joinable state. To avoid this, join() the thread(s) before destroying them.
The operating system is under no obligation to run your other threads when you sleep(2). It could let Google Chrome have that time slice, or it could use it to do its own background tasks, or it could just sit there on its thumbs.
That logic you just went through of "This thread should only last two seconds at most, so sleeping will do it" is called a race condition. You've got two threads and you're making big assumptions about what order things in those threads will happen, without actually enforcing those assumptions. Effectively, your threads enter into a race: if the three child threads win the race, then your program works fine, but if the main thread wins the race, then your program exhibits undefined behavior. And if your program has a chance of exhibiting undefined behavior, then that means that your program's behavior is undefined.
By adding the join calls, you enforce your assumption. You demand that the main thread cannot exit until the other three threads finish, which is what you were implicitly assuming before. This makes your program's behavior defined.

Proper way to terminate a thread in c++

I'm learning about multithreading and I wrote this code:
#include <iostream>
#include <mutex>
#include <thread>
#include <string>
#include <chrono>
#include <condition_variable>
int distance = 20;
int distanceCovered = 0;
std::condition_variable cv;
std::mutex mu;
void keep_moving(){
while(true){
std::cout << "Distance is: " << distanceCovered << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
distanceCovered++;
if(distanceCovered == distance){
cv.notify_one();
std::terminate();
}
}
}
void wake_me_up()
{
std::unique_lock<std::mutex> ul(mu);
cv.wait( ul, []{ return distanceCovered==distance; }); // protects the lines of code below
std::cout << "I'm here" << std::endl;
std::terminate();
}
int main() {
std::thread driver(keep_moving);
std::thread wake_me(wake_me_up);
driver.join();
wake_me.join();
system("pause");
return 0;
}
As you can see thread 'keep_moving' counts from 0-20 in 20 seconds and then notifies the 'wake_me_up' thread which prints "I'm here" and then terminates. After notifying the thread the 'keep_moving' thread also terminates.
Please tell me if I'm terminating the threads in a proper way. When I run this code I get the following message:
terminate called without an active exception
I'm here
terminate called recursively
Aborted
Thank you.
No. The correct (and only correct in standard C++) way to terminate a thread is to return from its thread function.
std::terminate kills your entire process. Even if it only killed the current thread (i.e. behaved like the Win32 TerminateThread function, which you should never call!), it would not unwind the stack, not call destructors, and thus possibly leave some necessary cleanup unfinished (like releasing mutexes).
std::terminate is meant to be used on a critical failure where your program cannot possibly continue. The message "without an active exception" is because the primary use of terminate is to kill the program if the exception system fails, e.g. due to a nested exception, so the function by default looks for an active exception and prints information about it.

What "detach()" on thread does? CPP

I know many people asked this question, but im not "many people" and I need a different and a better explanation to understand.
The member function "detach()" what exactly it does?
I tried running the next code sample:
#include <iostream>
#include <chrono>
#include <thread>
void independentThread()
{
std::cout << "Starting concurrent thread.\n";
std::this_thread::sleep_for(std::chrono::seconds(200));
std::cout << "Exiting concurrent thread.\n";
}
void threadCaller()
{
std::cout << "Starting thread caller.\n";
std::thread t(independentThread);
t.detach();
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Exiting thread caller.\n";
}
int main()
{
threadCaller();
std::this_thread::sleep_for(std::chrono::seconds(5));
}
And after 5 seconds the all program closed.
I thought the program will be opened another 195 seconds after the "main" closes, because the all idea of "detach" is that is independent with the main, so in independent way, it should still run untill the all detached therades are terminates...
I read the documentation and came to here.
A better explanation - PLEASE! :)
Detached thread is a thread you can't wait on to complete. std::thread destructor will check if the thread is either detached or joined, and if neither happened, will abort a program (call std::terminate).
After the main() terminates, program unconditionally terminates as well, not waiting for any threads, detached or otherwise.

Parent thread join(): Blocks Until Children Finish?

I have a C++ class that does some multi-threading. Consider the pseudo-code below:
void MyClass::Open() {
loop_flag = true;
// create consumer_thread (infinite loop)
// create producer_thread (infinite loop)
}
void MyClass::Close() {
loop_flag = false;
// join producer_thread
// join consumer_thread
}
MyClass::~MyClass() {
Close();
// do other stuff here
}
Note that consumer_thread, producer_thread, and their associated functions are all encapsulated in MyClass. The caller has no clue that their calls are multi-threaded and what's going on in the background.
Now, the class is part of a larger program. The program has some initial multi-threading to handle configuration of the system since there's a ton of stuff happening at once.
Like this (pseudo-code):
int main() {
// create config_thread1 (unrelated to MyClass)
// create thread for MyClass::Open()
// ...
// join all spawned configuration threads
}
So my question is, when I call join() for the thread linked to MyClass::Open() (i.e., the configuration thread spawned in main()), what happens? Does it join() immediately (since the MyClass::Open() function just returns after creation of producer_thread and consumer_thread) or does it wait for producer_thread and consumer_thread to finish (and therefore hangs my program).
Thanks in advance for the help. In terms of implementation details, I'm using Boost threads on a Linux box.
Edited to add this diagram:
main()
|
|
|
|--->configuration_thread (that runs MyClass::Open())
|
|
|----> producer_thread
|----> consumer_thread
If I call join() on configuration_thread(), does it wait until producer_thread() and consumer_thread() are finished or does it return immediately (and producer_thread() and consumer_thread() continue to run)?
A (non detached) thread will be joignable, even after having returned from the function it was set to run, until it has been joined.
Example:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void foo(){
std::cout << "helper: I'm done\n";
}
int main(){
cout << "starting helper...\n";
thread helper(foo);
this::thread::sleep_for(std::chrono::seconds(5));
cout << "helper still joignable?..." << (helper.joignable()?"yes!":"no...:(") << "\n";
helper.join();
cout << "helper joined!";
cout << "helper still joignable?..." << (helper.joignable()?"really?":"not anymore!") << "\n";
cout << "done!\n";
}
Output:
starting helper...
helper: I'm done
still joinable?...yes!
helper joined!
still joinable?...not anymore!
done!
As for how much time the join method takes, I don't think this is specified, but surely it doesn't't have to wait for all the other threads to finish, or it would mean that only one thread would be able to join all the others.
From §30.3.5:
void Join();
Requires: joinable() is true
Effects: Blocks until the thread represented by *this had completed.
Synchronization: The completion of the thread represented by *this synchronises with the corresponding successful join() return. [Note: Operations on *this are not synchronised. * -- end note*]
[...]

When should I use std::thread::detach?

Sometime I have to use std::thread to speed up my application. I also know join() waits until a thread completes. This is easy to understand, but what's the difference between calling detach() and not calling it?
I thought that without detach(), the thread's method will work using a thread independently.
Not detaching:
void Someclass::Somefunction() {
//...
std::thread t([ ] {
printf("thread called without detach");
});
//some code here
}
Calling with detaching:
void Someclass::Somefunction() {
//...
std::thread t([ ] {
printf("thread called with detach");
});
t.detach();
//some code here
}
In the destructor of std::thread, std::terminate is called if:
the thread was not joined (with t.join())
and was not detached either (with t.detach())
Thus, you should always either join or detach a thread before the flows of execution reaches the destructor.
When a program terminates (ie, main returns) the remaining detached threads executing in the background are not waited upon; instead their execution is suspended and their thread-local objects destructed.
Crucially, this means that the stack of those threads is not unwound and thus some destructors are not executed. Depending on the actions those destructors were supposed to undertake, this might be as bad a situation as if the program had crashed or had been killed. Hopefully the OS will release the locks on files, etc... but you could have corrupted shared memory, half-written files, and the like.
So, should you use join or detach ?
Use join
Unless you need to have more flexibility AND are willing to provide a synchronization mechanism to wait for the thread completion on your own, in which case you may use detach
You should call detach if you're not going to wait for the thread to complete with join but the thread instead will just keep running until it's done and then terminate without having the spawner thread waiting for it specifically; e.g.
std::thread(func).detach(); // It's done when it's done
detach basically will release the resources needed to be able to implement join.
It is a fatal error if a thread object ends its life and neither join nor detach has been called; in this case terminate is invoked.
This answer is aimed at answering question in the title, rather than explaining the difference between join and detach. So when should std::thread::detach be used?
In properly maintained C++ code std::thread::detach should not be used at all. Programmer must ensure that all the created threads gracefully exit releasing all the acquired resources and performing other necessary cleanup actions. This implies that giving up ownership of threads by invoking detach is not an option and therefore join should be used in all scenarios.
However some applications rely on old and often not well designed and supported APIs that may contain indefinitely blocking functions. Moving invocations of these functions into a dedicated thread to avoid blocking other stuff is a common practice. There is no way to make such a thread to exit gracefully so use of join will just lead to primary thread blocking. That's a situation when using detach would be a less evil alternative to, say, allocating thread object with dynamic storage duration and then purposely leaking it.
#include <LegacyApi.hpp>
#include <thread>
auto LegacyApiThreadEntry(void)
{
auto result{NastyBlockingFunction()};
// do something...
}
int main()
{
::std::thread legacy_api_thread{&LegacyApiThreadEntry};
// do something...
legacy_api_thread.detach();
return 0;
}
When you detach thread it means that you don't have to join() it before exiting main().
Thread library will actually wait for each such thread below-main, but you should not care about it.
detach() is mainly useful when you have a task that has to be done in background, but you don't care about its execution. This is usually a case for some libraries. They may silently create a background worker thread and detach it so you won't even notice it.
According to cppreference.com:
Separates the thread of execution from the thread object, allowing
execution to continue independently. Any allocated resources will be
freed once the thread exits.
After calling detach *this no longer owns any thread.
For example:
std::thread my_thread([&](){XXXX});
my_thread.detach();
Notice the local variable: my_thread, while the lifetime of my_thread is over, the destructor of std::thread will be called, and std::terminate() will be called within the destructor.
But if you use detach(), you should not use my_thread anymore, even if the lifetime of my_thread is over, nothing will happen to the new thread.
Maybe it is good idea to iterate what was mentioned in one of the answers above: When the main function is finished and main thread is closing, all spawn threads either will be terminated or suspended. So, if you are relying on detach to have a background thread continue running after the main thread is shutdown, you are in for a surprise. To see the effect try the following. If you uncomment the last sleep call, then the output file will be created and written to fine. Otherwise not:
#include <mutex>
#include <thread>
#include <iostream>
#include <fstream>
#include <array>
#include <chrono>
using Ms = std::chrono::milliseconds;
std::once_flag oflag;
std::mutex mx;
std::mutex printMx;
int globalCount{};
std::ofstream *logfile;
void do_one_time_task() {
//printMx.lock();
//std::cout<<"I am in thread with thread id: "<< std::this_thread::get_id() << std::endl;
//printMx.unlock();
std::call_once(oflag, [&]() {
// std::cout << "Called once by thread: " << std::this_thread::get_id() << std::endl;
// std::cout<<"Initialized globalCount to 3\n";
globalCount = 3;
logfile = new std::ofstream("testlog.txt");
//logfile.open("testlog.txt");
});
std::this_thread::sleep_for(Ms(100));
// some more here
for(int i=0; i<10; ++i){
mx.lock();
++globalCount;
*logfile << "thread: "<< std::this_thread::get_id() <<", globalCount = " << globalCount << std::endl;
std::this_thread::sleep_for(Ms(50));
mx.unlock();
std::this_thread::sleep_for(Ms(2));
}
std::this_thread::sleep_for(Ms(2000));
std::call_once(oflag, [&]() {
//std::cout << "Called once by thread: " << std::this_thread::get_id() << std::endl;
//std::cout << "closing logfile:\n";
logfile->close();
});
}
int main()
{
std::array<std::thread, 5> thArray;
for (int i = 0; i < 5; ++i)
thArray[i] = std::thread(do_one_time_task);
for (int i = 0; i < 5; ++i)
thArray[i].detach();
//std::this_thread::sleep_for(Ms(5000));
std::cout << "Main: globalCount = " << globalCount << std::endl;
return 0;
}