Zach
Zach

Reputation: 537

exiting the program in a multi-threades program

I'm writing a program that uses the POSIX thread library. I'm performing some return value of system calls, such as:

if (pthread_join(temp, NULL) != 0) {  
    cerr << "system error\n" << endl;  
    exit(1);  
}  

I want the program to exit immediately when it passes this if condition, but there could be a problem when the cpu decides to switch to a different thread right before the 'exit(1)' command.
Is there a way to protect such cases?

using a special mutex for this wouldn't help because: 1. i have many calls like this and locking each would make the code very slow, inefficient, and mostly - very ugly! 2. Each mutex requires its own return value check! So that obviously doesn't solve the initial problem..
Any helping ideas?

Upvotes: 3

Views: 189

Answers (2)

Chris Eberle
Chris Eberle

Reputation: 48795

Looks like there IS an answer for this, but I don't know how effective it is (i.e. if the program is already having issues, this may or may not work).

Can I prevent a Linux user space pthread yielding in critical code?

Upvotes: 0

Naszta
Naszta

Reputation: 7744

Use GCC atomic to write to a commonly used variable. Every thread should check this variable periodically. If this variable is changed, exit from the thread. The main thread do exit, when all other threads were finished.

One more link.

Upvotes: 1

Related Questions