alexander.sivak
alexander.sivak

Reputation: 4730

How an exit code is determined in a multithreaded program when one of the threads fails?

struct func
{
    int& i;
    func(int& i_):i(i_){}
    void operator()()
    {
        for (unsigned j = 0; j < 1000000; ++j)
        {
            ++i;
        }
    }
};

int main()
{
    int some_local_state = 0;
    func my_func(some_local_state);
    std::thread my_thread(my_func);
    my_thread.detach();
    return 0;
}

Output is

(process 1528) exited with code -1073741819

What determines the exit code? What does detaching mean for a Windows process?

Upvotes: 0

Views: 109

Answers (1)

prog-fh
prog-fh

Reputation: 16910

In this example, the error code -1073741819 (0xc0020001) is not produced by your executable but by the operating system which decided to kill your process.

You also asked a question (in the comments) about detaching a thread. This means that you will not use join() on this thread, thus you launch it, but you are not interested in knowing when it finishes its work.


EDIT

In my first answer I misread the example and thought the abrupt termination was due to an invalid memory access through the uninitialized i reference. It was wrong since i is actually initialised in order to reference some_local_state. However, when main() returns some_local_state does not exist anymore while being still referenced by the thread. Nothing is said about what happens to the detached thread at the exact moment when main() returns. Does this thread terminate immediately before the local variables of main() disappear? I really have doubts about this... This probably explains the abnormal termination of the process.

Upvotes: 1

Related Questions