python多任务及返回值的处理方法
2019/7/14 23:39:57
本文主要是介绍python多任务及返回值的处理方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
废话不多说,直接上代码!
# coding:utf-8 from multiprocessing import Pool import time def keywords(title, content, top_n=5): print u'关键词提取...' print title, content, top_n time.sleep(3) return 0, [u"晴", u"多云"] def category(title, content): print u'文本分类...' print title, content time.sleep(5) return 1, [u"天气"] def run(title, content): keywords_list = [] category_list = [] pool = Pool(processes=2) q = [] q.append(pool.apply_async(keywords, args=(title, content, 5))) q.append(pool.apply_async(category, args=(title, content))) for item in q: r = item.get() if r[0] == 0: keywords_list = r[1] elif r[0] == 1: category_list = r[1] pool.close() pool.join() return category_list, keywords_list if __name__ == "__main__": title = u"天气预报" content = u"北京今日天气:晴转多云" t1 = time.time() category_list, keywords_list = run(title, content) print "分类结果:", " ".join(category_list) print "关键词提取结果", " ".join(keywords_list) print time.time() - t1
或者:
# coding:utf-8 from multiprocessing import Pool import time def keywords(title, content, top_n=5): print u'关键词提取...' print title, content, top_n time.sleep(3) return 0, [u"晴", u"多云"] def category(title, content): print u'文本分类...' print title, content time.sleep(5) return 1, [u"天气"] def run(title, content): keywords_list = [] category_list = [] pool = Pool(processes=2) q = [] q.append(pool.apply_async(keywords, args=(title, content, 5))) keywords_list = [w["word"] for w in q[0].get()[1]] category_list = category(title, content)[1] pool.close() pool.join() return category_list, keywords_list if __name__ == "__main__": title = u"天气预报" content = u"北京今日天气:晴转多云" t1 = time.time() category_list, keywords_list = run(title, content) print "分类结果:", " ".join(category_list) print "关键词提取结果", " ".join(keywords_list) print time.time() - t1
以上这篇python多任务及返回值的处理方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持找一找教程网。
这篇关于python多任务及返回值的处理方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python