操作系统中,进程是资源分配的基本单位,线程是PU调度(程序执行)的最小单位。计算机执行程序必须分配资源(内存,有堆、栈、自右存储区、全局/静态变量区、数据区)
1.多线程
关于多线程的介绍,这不再阐述,请见python内置函数thread
相关操作:
# encoding:utf-8
# 多线程测试
import time
import threading
def test_thread(para='hi',sleep=3):
time.sleep(sleep)
j = 1
for i in range(10000):
j += 1
print(j)
def main():
# 创建线程
print('启动线程.....')
thread_hi = threading.Thread(target=test_thread)
thread_hello = threading.Thread(target=test_thread,args=('hello',1))
# 启动线程
thread_hi.start()
thread_hello.start()
print('Main thread has ended!')
if __name__ == '__main__':
t1 = time.time()
main()
print(time.time() - t1)
print('不使用线程...')
t2 = time.time()
test_thread()
print(time.time() - t2)
具体案例:
现有新浪新闻分类数据,数据文件格式如下:
cnews下存在14个类型的新闻数据,每个类别下有一系列的新闻文本内容。现需将所有的新闻数据按照 类型+tab+文本内容存放在txt文件中。据统计,cnews下每个类型的新闻有如下图的文件数目。
{'体育': 131604, '娱乐': 92632, '家居': 32586, '彩票': 7588, '房产': 20050, '教育': 41936,
'时尚': 13368,'时政': 63086, '星座': 3578, '游戏': 24373, '社会': 50849, '科技': 162929,
'股票': 154398, '财经': 37098}
多线程处理这些文件,并保存为train,dev,test三文件形式,其代码如下:
# encoding:utf-8
import os
import random
import time
import threading
def getpath(path='cnews'):
return os.path.abspath(os.path.dirname('__file__')) + os.path.sep + path
def labelFileOrg(num=2000):
cnews_label = ['cnews\\' + ch for ch in os.listdir(getpath('cnews')) if '\u4e00' <= ch <= '\u9fff'] # 判断ch是否为中文
cnew_label_file = dict()
for ch in cnews_label:
print('新闻类型:',ch)
file_list = os.listdir(getpath(ch))
random.shuffle(file_list)
cnew_label_file[ch] = file_list[:num]
for file_name in file_list[:int(num * 0.7)]:
writeFile(ch,getpath(ch + '\\' + file_name))
for file_name in file_list[int(num * 0.7 + 1):int(num * 0.9)]:
writeFile(ch,getpath(ch + '\\' + file_name),'cnews\\cnews.dev.txt')
for file_name in file_list[int(num * 0.9 + 1):num]:
writeFile(ch,getpath(ch + '\\' + file_name),'cnews\\cnews.test.txt')
def writeFile(ch,filename,path='cnews\\cnews.train.txt'):
with open(filename,'rb') as fp:
text = ' '.join([line.decode().strip('\n') for line in fp.readlines()])
text = ch[6:] + ' ' + text
with open(path,'a',encoding = 'utf-8') as fp:
fp.writelines(text + '\n')
def main():
# 创建线程
print('启动线程.....')
thread_hi = threading.Thread(target=labelFileOrg)
thread_hello = threading.Thread(target=labelFileOrg,args=('hello',1))
# 启动线程
thread_hi.start()
thread_hello.start()
print('Main thread has ended!')
if __name__ == '__main__':
t1 = time.time()
main()
print(time.time() - t1)
2. 异步编程
python中最常见的异步编程操作,是用asyncio模块。详细使用介绍见Python 异步编程入门
使用方法
# encoding = utf-8
import asyncio
async def count():
print("One")
await asyncio.sleep(1)
print("Two")
async def main():
await asyncio.gather(count(), count(), count())
asyncio.run(main())