3

I have this code:

#include "stdafx.h"
#include <iostream>
#include <future>
#include <chrono>

int main()
{
    bool bExit = false;
    int iSeconds = 0; 

    std::thread t([&]()
    {
        std::this_thread::sleep_for(std::chrono::seconds{ 10 });
        bExit = true;
    });

    while (!bExit)
    {
        std::this_thread::sleep_for(std::chrono::seconds{ 1 });
        std::cout << "SECONDS PASSED: " << ++iSeconds << std::endl;
    };

    //t.join();

    std::cout << "PRESS ENTER TO EXIT";
    getchar();

    return 0;
}

I don't understand why if I don't call t.join() I get an "abort() has been called" error. I've checked with the debugger and the new thread ceases to exist as soon the lambda exits. Apart from the specific error, is it safe using lambdas in this manner and never call joins?

My ultimate goal is to create some one time execution launch and forget lambdas for delayed execution, and maybe std::thread isn't the best way, so if someone has some advise on a better way to implement it...

Many thanks in advance

Kiske1
  • 408
  • 3
  • 15
  • 3
    `~std::thread` calls `std::terminate` if the thread is still `joinable()`. Just `detach()` if you don't want to `join` it. – Zeta Oct 18 '16 at 15:23
  • 1
    You can use [`thread::detach`](http://en.cppreference.com/w/cpp/thread/thread/detach) – Karsten Koop Oct 18 '16 at 15:24
  • 1
    @Zeta should've made that an answer - because this is the answer to "I don't understand why" which is the important question. – UKMonkey Oct 18 '16 at 15:26
  • 1
    @UKMonkey: I was rather sure that this was a duplicate of another question, tbh. – Zeta Oct 18 '16 at 15:33
  • There are indeed other questions on the topic, but I haven't find an answer to my very specific questions. I can't still understend why i get the "abort()" error. in the other posts the posters used functions and not lambdas which I suppose are threated like normal functions, but I'm not sure about it – Kiske1 Oct 18 '16 at 15:43

0 Answers0