SoFunction
Updated on 2024-11-17

python implementation of running a function in each separate process

This article is an example of a python implementation that runs a function in each separate process. Shared for your reference. Specific analysis is as follows:

This simple function is equivalent to running another function in a separate process, which is useful for freeing up memory resources.

#!/usr/bin/env python
from __future__ import with_statement
import os, cPickle
def run_in_separate_process(func, *args, **kwds):
  pread, pwrite = ()
  pid = ()
  if pid > 0:
    (pwrite)
    with (pread, 'rb') as f:
      status, result = (f)
    (pid, 0)
    if status == 0:
      return result
    else:
      raise result
  else: 
    (pread)
    try:
      result = func(*args, **kwds)
      status = 0
    except Exception, exc:
      result = exc
      status = 1
    with (pwrite, 'wb') as f:
      try:
        ((status,result), f, cPickle.HIGHEST_PROTOCOL)
      except , exc:
        ((2,exc), f, cPickle.HIGHEST_PROTOCOL)
    os._exit(0)
#an example of use
def treble(x):
  return 3 * x
def main():
  #calling directly
  print treble(4)
  #calling in separate process
  print run_in_separate_process(treble, 4)

I hope that what I have described in this article will help you in your Python programming.