'''进程''' from multiprocessing import Process import os,time def run(name): print('运行子进程%s(%s)'%(name,os.getpid())) def run2(name): print('运行子进程是%s(%s)'%(name,os.getpid())) if __name__ == "__main__": print('当前子进程%s'%os.getpid()) # run('test') # 这行代码仍然在当前进程中执行 # 创建一个新的进程 p = Process(target=run,args=('test',)) print('开始执行子进程') # 开始执行新进程 p.start() # time.sleep(1) # 将子进程加入到主进程中 p.join() print('子进程执行完毕') p2 = Process(target=run2,args=('test',)) p2.start() p2.join() '''进程池''' from multiprocessing import Pool import os,time,random def task(name): print('运行任务%s(%s)'%(name,os.getpid())) start = time.time() # 随机休眠1-3秒 time.sleep(random.randint(1,3)) end = time.time() print('任务%s耗时为%.2f'%(name,(end-start))) if __name__ == '__main__': print('主进程是%s'%os.getpid()) # 初始化进程池 pool = Pool(4) for i in range(6): # 将任务交给进程池去执行 pool.apply_async(task,args=('任务%d'%i,)) pool.close() pool.join() '''线程''' import threading,time def task(name): print('线程%s正在运行...'%threading.current_thread().name) print(name) if __name__ == '__main__': print('主线程%s'%threading.current_thread().name) # task() # 创建一个新线程 t = threading.Thread(target=task,args=('传入一个参数',)) t.start() t.join() print('主线程%s运行结束'%threading.current_thread().name) ''' 多线程安全问题 python 中多任务一般使用多进程来完成 因为在python中多线程并不能真正提高效率 进程可以在不同的电脑上运行——分布式 ''' import threading,time # 银行账户 balance = 0 # 创建一个锁 lock = threading.Lock() def change(money): global balance # 存钱 balance = balance + money balance = balance - money def run(money): for i in range(100000): # 上锁 lock.acquire() try: change(money) finally: # 释放锁 lock.release() t1 = threading.Thread(target=run,args=(10,)) t2 = threading.Thread(target=run,args=(8,)) t1.start() t2.start() t1.join() t2.join() print('balance=%d'%balance) ''' t1: x1 = balance + 10 balance = x1 x1 = balance - 10 balance = x1 t2: x2 = balance + 8 balance = x2 x2 = balance - 8 balance = x2 balance = 0 ----------------------------- t1.x1 = balance + 10 t2.x2 = balance + 8 t2.balance = x2 balance = 8 t1.balance = x1 balance = 10 t1.x1 = balance - 10 x1 = 0 t1.balance = x1 balance = 0 x2 = balance - 8 x2 = -8 balance = x2 balance = -8 ''' import mysql.connector # 连接数据库 db = mysql.connector.connect(host='localhost',user='root',password='123456',port='3308' # 获取游标 cursor = db.cursor() # 创建数据库 cursor.execute('CREATE DATABASE JY40') ''' ACID Atomic 原子性 Consistenec 一致性 Isolation 隔离性 Duration 持久性 ''' import mysql.connector # 连接到指定数据库 db = mysql.connector.connect(host='localhost',user='root',password='123456',port='3308',database='JY40') # 获取游标 cursor = db.cursor() # 获取一个user表 # cursor.execute( # ''' # CREATE TABLE USER2( # id INT, # NAME VARCHAR(20), # pwd VARCHAR(20) # ) # ''' # ) # 添加数据 cursor.execute('insert into user(name,pwd) values("tom","123")') # 提交 db.commit()
|