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

首頁 > 編程 > Python > 正文

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

2020-02-23 00:49:52
字體:
來源:轉載
供稿:網友

本文實例講述了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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 德惠市| 武乡县| 原平市| 屯留县| 崇州市| 闽侯县| 尖扎县| 武山县| 芜湖市| 新营市| 宜兰市| 伊宁市| 定日县| 资阳市| 确山县| 科技| 毕节市| 绥宁县| 化隆| 喀喇沁旗| 梅州市| 收藏| 齐齐哈尔市| 阳新县| 台前县| 高邑县| 杭锦后旗| 乐平市| 青岛市| 建湖县| 内黄县| 建宁县| 芷江| 东至县| 吴堡县| 霍林郭勒市| 仁布县| 清远市| 高唐县| 雷州市| 五河县|