Refactor *_work and execute_graph.

The boilerplate part of the *_work functions is moved to a separate
function named run_thread. This function calls the actual *_work
functions.