Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c++ - std::thread - "terminate called without an active exception", don't want to 'join' it

As per This Question, I'm using a thread to terminate a function on user input. My code looks something like:

bool stopper = false;
thread stopThread(userStop, &stopper);      // start thread looking for user input
for(int i = 0; i < 1000; i++) {
    if(stopper) { break; }                  // break if desired
    // Do stuff
}
return 0;

where,

userStop(bool *st) {
    char chChar = getchar();
    if(chChar == '
') {
        *st = true;
    }
}

When I run this, I get the error terminate called without an active exception. Based on these questions: thread terminate called without an active exception, C++ terminate called without an active exception; it looks like its because I'm not 'join'ing the thread again.

The problem is, I don't want to 'join' the thread -- because then the user will need to provide input for userStop()to terminate, but I only want the user to provide input if the for-loop is to be broken (which it isn't necessarily).

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The trouble you are encountering is a result of the stopThread going out of scope on the stack. The C++ standard has the following to say about this:

30.3.1.3 thread destructor [thread.thread.destr]

~thread();

If joinable() then terminate(), otherwise 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 raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable. — end note ]

What this means is that you should not let threads go out of scope without first calling either join() or detach().

The way you describe it, you want the thread to go out of scope without joining so it will continue to run as your application runs. That requires a call to detach(). From there, I can only offer a little wisdom...

  • That thread is now completely responsible for its own lifetime. If it doesn't return on its own, it will run forever (until the process terminates).

  • You are getting user input, presumably from something like cin or getch(). If these are accessed from multiple threads, you do not have much assurance that there are not race conditions in their library implementations. Tread lightly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...