C++ How to gracefully exit multiprocessing

  • C/++/#
  • Thread starter Bill Simpson
  • Start date
  • #1
1,069
29

Main Question or Discussion Point

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, cout 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, cout 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?
 

Answers and Replies

  • #2
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
683
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.
 

Related Threads on C++ How to gracefully exit multiprocessing

Replies
5
Views
696
  • Last Post
Replies
10
Views
5K
  • Last Post
Replies
9
Views
673
  • Last Post
Replies
15
Views
3K
  • Last Post
Replies
9
Views
4K
Replies
10
Views
17K
  • Last Post
Replies
8
Views
6K
Top