python多线程
# 多进程,
import os
import time
from multiprocessing import Process
# 启动时必须在 if __name__ 判断下,windows 必须,其他 无限制
# =================================================
# def func(args):
# print("子进程:",os.getpid())
# print("子进程的父进程:",os.getppid())
# time.sleep(10)
# print("子进程结束")
# if __name__ =="__main__":
# p = Process(target=func,args=(1,)) # 注册 并传入元祖 元祖有一个参数要加逗号
# # p是进程对象
# p.start() # 开启子进程
# print("主进程:", os.getpid())
# print("主进程的父进程:",os.getppid()) # cmd 或者是 pycharm
# 生命周期
# 主进程长:自己执行完结束
# 子进程长:等待子进程结束
# =================================================
# 多进程中的方法
# join
# def fun(arg1,arg2):
# print('*'*arg1)
# # time.sleep(5)
# print('*'*arg2)
# if __name__ == "__main__":
# p = Process(target=fun,args=(10,20))
# p.start()
# # p.join() # 感知子进程结束
# # time.sleep(1)
# print("all is stop")
#
# print("最后的语句")
# os.walk(r"目录") # 返回 文件夹中文件名字
# =================================================
# def fun():
# print("xxx")
# if __name__ == "__main__":
# for i in range(10):
# p = Process(target=fun)
# p.start()
# p.join() # 停止for循环 进程结束后继续
# print("for")
# print("主进程")
# =================================================
# 第二种方法
# class MyProcess(Process):
# def __init__(self,args):
# super().__init__() # 若要传递参数,需要调用父类init
#
# def run(self):
# print("子进程",self.__dict__)
# print(self.pid)
# if __name__ == "__main__":
# print("主进程:",os.getpid())
# p1 = MyProcess()
# p1.start()
# =================================================
# 进程之间数据是隔离,命名空间不通
# def fun():
# global n
# n= 0
# print("pid:%s" %os.getpid(),n)
# if __name__ == "__main__":
# n=100
# p = Process(target=fun)
# p.start()
# p.join()
# print(n) # -->100
# =================================================
# 多进程tcp连接
# import socket
# # 客户端
# sk = socket.socket()
# sk.connect(("127.0.0.1",8080))
# sk.send('N好'.encode("utf8"))
# msg = sk.recv(1024).decode("utf8")
# print(msg)
# sk.close()
#
# # 服务端
# def server(conn):
# ret= "你好".encode("utf8")
# conn.send(ret)
# msg = conn.recv(1024).decode("utf8")
# print(msg)
# conn.close()
#
# sk = socket.socket()
# sk.bind(("127.0.0.1",8080))
# sk.listen()
# if __name__ == "__main__":
# while True:
# conn, addr = sk.accept()
# p = Process(target=server,args=(conn,))
# p.start()
# =================================================
# 守护进程
# 默认情况 父进程 等待子进程结束
# p.daemon = True 在start前,设置为守护进程,守护进程随父进程(代码执行完毕)结束
# 若父进程在等待 子进程(非守护进程时) ,若父进程代码完毕,守护进程应该结束
# p.is_alive() 判断进程是否存活
# p.terminate() 终止进程
# =================================================
# 锁
# 未加锁实例:
# 火车票
import json
import time
from multiprocessing import Process
# def show(i):
# with open('ticket') as f:
# dic = json.load(f)
# print('余票: %s'%dic['ticket'])