风-fmgao

导航

进程与线程区别

#!/usr/bin/env python
# encoding: utf-8  
# Date: 2018/6/18


# 1、开进程的开销远大于开线程的
# import time
# from threading import Thread
# from multiprocessing import Process
#
#
# def task(name):
#     print('%s is running ' % name)
#     time.sleep(2)
#     print('%s is done' % name)
#
#
# if __name__ == '__main__':
#     # t1 = Thread(target=task, args=('线程1', ))
#     # t1.start()
#     p1 = Process(target=task, args=('线程1',))
#     p1.start()
#     print('主线程')

# 2、同一个进程内的线程共享该进程的地址空间
# from threading import Thread
# from multiprocessing import Process
# n = 100
#
#
# def task():
#     global n
#     n = 0
#
#
# if __name__ == '__main__':
#     t1 = Thread(target=task, )
#     t1.start()
#     t1.join()  # 主 0
#     # p1 = Process(target=task, )
#     # p1.start()
#     # p1.join()
#     print('主', n)  # 主 100

# 3、瞅一眼pid
# from multiprocessing import Process, current_process
# import os
#
#
# def task():
#     # print(current_process().pid)
#     print('子进程pid:%s  父进程pid: %s' % (os.getpid(), os.getppid()))
#
#
# if __name__ == '__main__':
#     p1 = Process(target=task, )
#     p1.start()
#     # print('主', current_process().pid)
#     print('主', os.getpid())  # 作用同上一行代码

from threading import Thread
import os


def task():
    print('子线程pid:%s ' % (os.getpid()))  # 子线程pid:37352


if __name__ == '__main__':
    p1 = Thread(target=task, )
    p1.start()
    print('主', os.getpid())  # 主 37352



posted on 2018-06-18 09:47  风-fmgao  阅读(105)  评论(0编辑  收藏  举报