1、获取进程ID。(getpid)
os.getpid()
2、获取父进程ID。(getppid)
os.getppid()
3、获取线程ID。(get_ident)
(1)、进程内局部标识。
import threading
threading.get_ident()
threading.current_thread().ident
(2)、系统全局标识:python下使用ctypes获取threading线程id。
【使用线程池完成阻塞型任务】
#encoding=utf-8
#author: walker
#date: 2017-03-27
#summary: 使用线程池完成阻塞型任务
#Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
import time
import random
import threading
import concurrent.futures
#同步型任务
def TaskSync(taskid, sleepTime):
print('thread_%05d %s sleep %d ...' % (threading.get_ident(), taskid, sleepTime))
time.sleep(sleepTime) #睡觉任务
print('\t\tthread_%05d %s sleep %d over' % (threading.get_ident(), taskid, sleepTime))
return taskid, sleepTime
#处理所有任务
def ProcAll(taskList):
pool = concurrent.futures.ThreadPoolExecutor(4)
futureList = list()
for taskid, sleepTime in taskList: #提交所有任务
futureList.append(pool.submit(TaskSync, taskid, sleepTime))
totalSleepTime = 0
for future in concurrent.futures.as_completed(futureList):
task, sleepTime = future.result()
print('\t\t\t\t\t\t%s sleep %d over' % (task, sleepTime))
totalSleepTime += sleepTime
return totalSleepTime
if __name__ == '__main__':
startTime = time.time()
taskList = [('task_%d' % id, random.randint(1, 5)) for id in range(0, 9)]
print('taskList:%s' % repr(taskList))
totalSleepTime = ProcAll(taskList)
print('totalSleepTime: %d s' % totalSleepTime)
print('real cost time:%.2f' % (time.time() - startTime))
【使用单线程完成异步型任务】
#encoding=utf-8
#author: walker
#date: 2017-03-27
#summary: 使用单线程完成异步型任务
#Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
import asyncio
import time
import random
#协程型任务
async def TaskAsync(taskid, sleepTime):
print('%s sleep %d ...' % (taskid, sleepTime))
await asyncio.sleep(sleepTime) #睡觉任务
print('\t%s sleep %d over' % (taskid, sleepTime))
return taskid, sleepTime
#处理所有任务
async def ProcAll(taskList):
coroutineList = list()
for taskid, sleepTime in taskList:
coroutineList.append(asyncio.ensure_future((TaskAsync(taskid, sleepTime))))
totalSleepTime = 0
for f in asyncio.as_completed(coroutineList):
task, sleepTime = await f
print('\t\t\t%s sleep %d over' % (task, sleepTime))
totalSleepTime += sleepTime
return totalSleepTime
if __name__ == '__main__':
startTime = time.time()
taskList = [('task_%d' % id, random.randint(1, 5)) for id in range(0, 9)]
print('taskList:%s' % repr(taskList))
loop = asyncio.get_event_loop()
totalSleepTime = loop.run_until_complete(ProcAll(taskList))
print('totalSleepTime: %d s' % totalSleepTime)
print('real cost time:%.2f' % (time.time() - startTime))
相关阅读:
1、Python自定义进程池(生产者/消费者模型)
2、asyncio — Asynchronous I/O, event loop, coroutines and tasks
3、concurrent.futures — Launching parallel tasks
4、multiprocessing — Process-based parallelism
5、协程与async/await语法(PEP 0492 Coroutines with async and await syntax 中文翻译)
6、Python协程:从yield/send到async/await
*** walker ***