国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現在每個獨立進程中運行一個函數的方法

2019-11-25 17:40:39
字體:
來源:轉載
供稿:網友

本文實例講述了python實現在每個獨立進程中運行一個函數的方法。分享給大家供大家參考。具體分析如下:

這個簡單的函數可以同于在單獨的進程中運行另外一個函數,這對于釋放內存資源非常有用

#!/usr/bin/env pythonfrom __future__ import with_statementimport os, cPickledef run_in_separate_process(func, *args, **kwds):  pread, pwrite = os.pipe()  pid = os.fork()  if pid > 0:    os.close(pwrite)    with os.fdopen(pread, 'rb') as f:      status, result = cPickle.load(f)    os.waitpid(pid, 0)    if status == 0:      return result    else:      raise result  else:     os.close(pread)    try:      result = func(*args, **kwds)      status = 0    except Exception, exc:      result = exc      status = 1    with os.fdopen(pwrite, 'wb') as f:      try:        cPickle.dump((status,result), f, cPickle.HIGHEST_PROTOCOL)      except cPickle.PicklingError, exc:        cPickle.dump((2,exc), f, cPickle.HIGHEST_PROTOCOL)    os._exit(0)#an example of usedef treble(x):  return 3 * xdef main():  #calling directly  print treble(4)  #calling in separate process  print run_in_separate_process(treble, 4)

希望本文所述對大家的Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 岳阳市| 简阳市| 秦皇岛市| 陇南市| 绥中县| 茶陵县| 宁德市| 克山县| 连云港市| 滦南县| 富川| 五家渠市| 大连市| 大厂| 商丘市| 阿拉尔市| 胶南市| 当阳市| 中方县| 鹤庆县| 安仁县| 祁阳县| 思南县| 新安县| 南通市| 和政县| 武汉市| 高淳县| 札达县| 汨罗市| 靖安县| 柘城县| 浮梁县| 通化市| 巩义市| 年辖:市辖区| 光泽县| 子洲县| 成都市| 赤水市| 清远市|