1、获取进程ID。(getpid)
代码语言:javascript复制os.getpid()
2、获取父进程ID。(getppid)
代码语言:javascript复制os.getppid()
3、获取线程ID。(get_ident)
(1)、进程内局部标识。
代码语言:javascript复制import threading
threading.get_ident()
threading.current_thread().ident
(2)、系统全局标识:python下使用ctypes获取threading线程id。
【使用线程池完成阻塞型任务】
代码语言:javascript复制#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_d %s sleep %d ...' % (threading.get_ident(), taskid, sleepTime))
time.sleep(sleepTime) #睡觉任务
print('ttthread_d %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('tttttt%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))
【使用单线程完成异步型任务】
代码语言:javascript复制#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('ttt%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))