jeudi 30 novembre 2017

How do I kill all threads and cleanly exit my application when the process receives a signal?

I am working on a multi threaded application (probably using pthreads). The application is timing sensitive and in general needs to accomplish as much as possible as quick as possible before the allotted time runs out. The application maintains a master state data structure that retains what work is to be done, and whether or not it passed or failed if the work was attempted. Before the application exits it must print out the state structure to std out.

There is no threading contention to worry about or blocking, each thread is nicely self contained. In a normal run the threads would divvy up the work, accomplish it, synchronize (waiting for the last one to finish) and then return upwards to let the program print out its state to the console. Some threads may print to the console along the way, but generally speaking the state of the program is printed right before the application ends.

A requirement that we have to deliver is to make sure the application runs within n minutes. n is some arbitrary number of minutes supplied by configuration file, and n minutes may not be enough time for the application to complete or even attempt all of its assigned tasks, but regardless the application needs to get as much done as possible, and when the time elapses terminate the execution, printing out the state before it exits.

This application will need to trap signals, specifically alarms and then kill all threads and cleanly exit the application (printing out the state before it exits). A polling architecture is not a viable mechanism for checking if the time has elapsed, the application must respond to the alarm signal for determiniation that the applicaiton should end.

What I would like to do is that when the application is interrupted by SIGALRM, kill all the threads and then print out the accumulated state and exit the program; however from my reading using things like printf are not safe to do inside a signal handler because it can be interrupted. Im thinking of using goto's (dont tell Dijkstra...) and killing the threads, jumping to my output section and then killing the program, but Ive heard that goto's are not a good idea.

Aucun commentaire:

Enregistrer un commentaire