C++ How to gracefully exit multiprocessing

  • Context: C/C++ 
  • Thread starter Thread starter Bill Simpson
  • Start date Start date
  • Tags Tags
    C++
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 3K views
Bill Simpson
Messages
1,077
Reaction score
33
Not a homework problem.

I've written a little compute-intensive code. That only keeps one core busy. So I run four copies. But compute time is variable so I thought I'd try my hand at multiprocessing.

I can fork to create four processes. No problem.

I/O is from cin, count and the processes need to share these to get the work stream and report results. So create a pipe holding a magic cookie. When any process has completed crunching and needs to do I/O it waits on the pipe until it gets the cookie, does the I/O, puts the cookie back in the pipe and goes back to crunching. No problem.

Now the problem. When each process finally discovers the input stream of work has been exhausted I need to gracefully terminate the process. But a few Google searches tell me that if the process just exits it will tear down the shared cin, count and the other processes that are busy working won't be able to report their final results.

Is there a really simple solution to this problem?
 
Physics news on Phys.org
Bill Simpson said:
Is there a really simple solution to this problem?
Bottom line: Use the lightweight processes that you get with POSIX threads instead of the heavyweight processes that you get with fork.

One solution is to make a thread that wants to print something do so as follows: Lock a mutex, print the desired results, and finally unlock the mutex. Threads are simple and switching between threads is generally faster than is switching between heavyweight processes.