python学习8——线程与进程

互斥锁

当多个线程共享一个数据的时候,会进行同步控制。
某个线程要更改共享数据时,先将其锁定,此时资源的状态为"锁定",其他线程不能改变,只到该线程释放资源,将资源的状态变成"非锁定",其他的线程才能再次锁定该资源。互斥锁保证了每次只有一个线程进行写入操作,从而保证了多线程情况下数据的正确性。

import threading
import time

# 互斥锁,当一个执行完毕,执行另外一个

num = 100
def demo1(nums, mutex):
    global num

    # 加锁
    mutex.acquire()
    for i in range(nums):
        num+=1
    mutex.release()
    print(f"demo1------{num}")


def demo2(nums, mutex):
    global num
    mutex.acquire()
    for i in range(nums):
        num += 1
    mutex.release()
    print(f"demo2------{num}")


def main():
	# 创建互斥锁对象
    mutex = threading.Lock()
  
    t1 = threading.Thread(target=demo1,args=(100000, mutex))
    t2 = threading.Thread(target=demo2,args=(100000, mutex))
    t1.start()
    t2.start()

    time.sleep(1)  
    #等待子线程执行完毕之后,再执行主程序
    print(f"main-----{num}")

if __name__ == '__main__':
    main()
  • 创建锁:mutex = threading.Lock()
  • 锁定: mutex.acquire()
  • 解锁: mutex.release()

死锁

在线程共享多个资源的时候,如果两个线程分别占有一部分资源并且等待对方资源的时候,就会产生死锁现象。

import threading
import time

class MyThread1(threading.Thread):
    def run(self):
        # 对mutexA上锁
        mutexA.acquire()

        # mutexA上锁后,延时1秒,等待另外那个线程 把mutexB上锁
        print(self.name+'----do1---up----')
        time.sleep(1)

        # 此时会堵塞,因为这个mutexB已经被另外的线程抢先上锁了
        mutexB.acquire()
        print(self.name+'----do1---down----')
        mutexB.release()

        # 对mutexA解锁
        mutexA.release()

class MyThread2(threading.Thread):
    def run(self):
        # 对mutexB上锁
        mutexB.acquire()

        # mutexB上锁后,延时1秒,等待另外那个线程 把mutexA上锁
        print(self.name+'----do2---up----')
        time.sleep(1)

        # 此时会堵塞,因为这个mutexA已经被另外的线程抢先上锁了
        mutexA.acquire()
        print(self.name+'----do2---down----')
        mutexA.release()

        # 对mutexB解锁
        mutexB.release()

mutexA = threading.Lock()
mutexB = threading.Lock()

if __name__ == '__main__':
    t1 = MyThread1()
    t2 = MyThread2()
    t1.start()
    t2.start()

重入锁

可以使一个线程多次锁定一个资源。就是线程A锁定资源之后,可以再次锁定。
下面这种多层加锁的情况下,使用Lock会导致阻塞的


import threading
import time


mutexA = threading.Lock()
mutexB = threading.Lock()
class MyThread1(threading.Thread):
    def run(self):
        mutexA.acquire()  # 双层上锁要RLock,上锁解锁需要成对出现
        mutexA.acquire()
        print(self.name+"A上锁啦")
        time.sleep(2)
        print(self.name + "A上锁啦")
        time.sleep(2)

        mutexB.acquire()
        print(self.name+"B上锁")
        mutexB.release()
        print(self.name+"B解锁啦")

        mutexA.release()
        print(self.name+"A解锁啦")
class MyThread2(threading.Thread):
    def run(self):
        mutexB.acquire()
        print(self.name+"B上锁了")
        time.sleep(2)

        mutexA.acquire()
        print(self.name+"A上锁")
        mutexA.release()
        print(self.name+"A解锁")
        mutexB.release()
        print(self.name+"B解锁")

if __name__ == '__main__':
    t1 = MyThread1()
    t2 = MyThread2()
    t1.start()
    t2.start()

线程同步

threading.Condition() 完成线程同步
实现下面这个例子:
天猫精灵:小爱同学
小爱同学:在
天猫精灵:现在几点了?
小爱同学:你猜猜现在几点了

import threading
from threading import Condition # 线程同步
class XiaoAi(threading.Thread):
    def __init__(self,mutex,con):
        super().__init__()
        self.name = "小爱同学"
        self.mutex = mutex
        self.con = con
    def run(self):
        with self.con:
            self.con.wait()
            print(f"{self.name}:在")
            self.con.notify()
            self.con.wait()
            print(f"{self.name}:你猜猜现在几点了")

class TianMao(threading.Thread):
    def __init__(self, mutex,con):
        super().__init__()
        self.name = "天猫精灵"
        self.mutex = mutex
        self.con = con
    def run(self):
        with self.con:
            print(f"{self.name}:小爱同学")
            self.con.notify()

            self.con.wait()
            print(f"{self.name}:现在几点了?")
            self.con.notify()
            
if __name__ == '__main__':
    mutex = threading.RLock()
    con  = Condition()
    t1 = XiaoAi(mutex,con)
    t2 = TianMao(mutex,con)
    t1.start()
    t2.start()
  • Condition(): 线程同步
  • wait() :等待
  • notify():唤醒

多进程

multiprocessing.Process() 实现多进程

import os

from multiprocessing import Process
def demo1():
    print("子进程1")
    print(f"子进程PID:{os.getpid()},父进程PPID:{os.getppid()}")


def demo2():
    print("子进程2")
    print(f"子进程PID:{os.getpid()},父进程PPID:{os.getppid()}")


if __name__ == '__main__':
    p1 = Process(target=demo1)
    p2 = Process(target=demo2)
    p1.start()
    p2.start()
    """
    父进程创建的叫子进程,每个子进程都有一个不重复的ID号,
    子进程与父进程的资源+代码一致,子进程从父进程继承了多个值的拷贝
    """
    print(f"主进程PID:{os.getpid()},父进程PPID:{os.getppid()}")

从输出结果我们能看出,主进程,也就是整个py文件的进程ID,是两个子进程的父进程PPID
在这里插入图片描述

Process 保护主进程

使用daemon = True来保护主进程

import time
from multiprocessing import Process

def demo():
    while True:
        print("---1----")
        time.sleep(1)

def demo2():
    while True:
        print("----2----")
        time.sleep(1)

if __name__ == '__main__':
    p1 = Process(target=demo)
    p2 = Process(target=demo2)
    p1.daemon = True
    p2.daemon = True # 保护主进程

    p1.start()
    p2.start()
    # p1.join()
    # p2.join() # 守护子进程
    print("主进程")

使用多线程进行udp_socket

可以实现同时发送并接收数据

import socket
import  threading
def recv_msg(udp_s):
    while True:
        recv_data = udp_s.recvfrom(1024)
        print(recv_data)

def send_msg(udp_s, dest_ip, dest_port):
    while True:
        send_data = input("请输入要发送的数据:")
        udp_s.sendto(send_data.encode("gbk"),(dest_ip, dest_port))

def main():
    udp_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    udp_s.bind(("", 7979))
    dest_ip = input("请输入对方的Ip:")
    dest_port = int(input("请输入对方的port:"))

    t_recv = threading.Thread(target=recv_msg, args=(udp_s,))
    t_send = threading.Thread(target=send_msg, args=(udp_s,dest_ip, dest_port))

    t_recv.start()
    t_send.start()

if __name__ == '__main__':
    main()
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQLAlchemy 是一个 SQL 工具包和对象关系映射(ORM)库,用于 Python 编程语言。它提供了一个高级的 SQL 工具和对象关系映射工具,允许开发者以 Python 类和对象的形式操作数据库,而无需编写大量的 SQL 语句。SQLAlchemy 建立在 DBAPI 之上,支持多种数据库后端,如 SQLite, MySQL, PostgreSQL 等。 SQLAlchemy 的核心功能: 对象关系映射(ORM): SQLAlchemy 允许开发者使用 Python 类来表示数据库表,使用类的实例表示表中的行。 开发者可以定义类之间的关系(如一对多、多对多),SQLAlchemy 会自动处理这些关系在数据库中的映射。 通过 ORM,开发者可以像操作 Python 对象一样操作数据库,这大大简化了数据库操作的复杂性。 表达式语言: SQLAlchemy 提供了一个丰富的 SQL 表达式语言,允许开发者以 Python 表达式的方式编写复杂的 SQL 查询。 表达式语言提供了对 SQL 语句的灵活控制,同时保持了代码的可读性和可维护性。 数据库引擎和连接池: SQLAlchemy 支持多种数据库后端,并且为每种后端提供了对应的数据库引擎。 它还提供了连接池管理功能,以优化数据库连接的创建、使用和释放。 会话管理: SQLAlchemy 使用会话(Session)来管理对象的持久化状态。 会话提供了一个工作单元(unit of work)和身份映射(identity map)的概念,使得对象的状态管理和查询更加高效。 事件系统: SQLAlchemy 提供了一个事件系统,允许开发者在 ORM 的各个生命周期阶段插入自定义的钩子函数。 这使得开发者可以在对象加载、修改、删除等操作时执行额外的逻辑。
SQLAlchemy 是一个 SQL 工具包和对象关系映射(ORM)库,用于 Python 编程语言。它提供了一个高级的 SQL 工具和对象关系映射工具,允许开发者以 Python 类和对象的形式操作数据库,而无需编写大量的 SQL 语句。SQLAlchemy 建立在 DBAPI 之上,支持多种数据库后端,如 SQLite, MySQL, PostgreSQL 等。 SQLAlchemy 的核心功能: 对象关系映射(ORM): SQLAlchemy 允许开发者使用 Python 类来表示数据库表,使用类的实例表示表中的行。 开发者可以定义类之间的关系(如一对多、多对多),SQLAlchemy 会自动处理这些关系在数据库中的映射。 通过 ORM,开发者可以像操作 Python 对象一样操作数据库,这大大简化了数据库操作的复杂性。 表达式语言: SQLAlchemy 提供了一个丰富的 SQL 表达式语言,允许开发者以 Python 表达式的方式编写复杂的 SQL 查询。 表达式语言提供了对 SQL 语句的灵活控制,同时保持了代码的可读性和可维护性。 数据库引擎和连接池: SQLAlchemy 支持多种数据库后端,并且为每种后端提供了对应的数据库引擎。 它还提供了连接池管理功能,以优化数据库连接的创建、使用和释放。 会话管理: SQLAlchemy 使用会话(Session)来管理对象的持久化状态。 会话提供了一个工作单元(unit of work)和身份映射(identity map)的概念,使得对象的状态管理和查询更加高效。 事件系统: SQLAlchemy 提供了一个事件系统,允许开发者在 ORM 的各个生命周期阶段插入自定义的钩子函数。 这使得开发者可以在对象加载、修改、删除等操作时执行额外的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值