首页 > 编程语言 >UUID与Python线程同步方式

UUID与Python线程同步方式

时间:2023-04-24 10:23:00浏览次数:47  
标签:__ UUID Python self threading 线程 import def

UUID是如何保证唯一性

高可靠,32位16进制数,32*4=128位二进制数,UUID4重复概率1/(2^128),加上时间戳应该好点,UUID1好点。

UUID Version 1:基于时间的UUID

时间戳、随机数和机器MAC地址得到。常用

UUID Version 2:DCE安全的UUID

UUID1的时间戳前4位置换为POSIX的UID或GID

UUID Version 3:基于名字的UUID(MD5)

计算名字和名字空间的MD5散列值得到,相同名字空间中相同名字的UUID重复生成是相同的。

UUID Version 4:随机UUID

随机数。

UUID Version 5:基于名字的UUID(SHA1)

计算名字和名字空间的SHA1值得到。

Python线程同步

昨天面试了一家单位,我果然啥都不会via,几分钟就结束了,觉得Python线程同步肯定有用吧,记一下。

临界资源

就是只能有一个线程访问的一块代码,需要进行原子操作的那部分。

1、通过锁:threading.Lock

线程共享Num类,访问前需要先获得锁。防止加法出错。另外,RLock操作可重入,同一个线程内多次acquire(),程序不会堵塞,但是需要相同的release。

import threading
import time


class Num:
    def __init__(self):
        self.num = 0
        self.lock = threading.Lock()

    def add(self):
        self.lock.acquire()  # 加锁,锁住相应的资源
        self.num += 1
        self.lock.release()  # 解锁,离开该资源


n = Num()


class jdThread(threading.Thread):
    def __init__(self):
        super().__init__()

    def run(self):
        for i in range(10000000):
            n.add()


if __name__ == '__main__':
    list_thread = [jdThread() for i in range(2)]
    [t.start() for t in list_thread]
    [t.join() for t in list_thread]
    print(n.num)

2、信号量threading.Semaphore

控制同时访问的个数,在执行IO密集型任务时。另外,boundageSamephore用于超过release时的抛出异常。

import threading
import time


class Num:
    def __init__(self):
        self.num = 0
        self.sem = threading.Semaphore(value=1)

    def add(self):
        self.sem.acquire()  # 加锁,锁住相应的资源
        print(self.num)
        time.sleep(0.1)
        self.sem.release()  # 解锁,离开该资源


n = Num()


class jdThread(threading.Thread):
    def __init__(self):
        super().__init__()

    def run(self):
        for i in range(10):
            n.add()


if __name__ == '__main__':
    list_thread = [jdThread() for i in range(2)]
    [t.start() for t in list_thread]
    [t.join() for t in list_thread]
    print(n.num)

3、条件量threading.Condition()

生产者消费者模式,wait进入等待状态,notify恢复运行

import threading
import time


class Goods:  # 产品类
    def __init__(self):
        self.count = 0

    def add(self, num=1):
        self.count += num

    def sub(self):
        if self.count > 0:
            self.count -= 1

    def empty(self):
        return self.count <= 0


class Producer(threading.Thread):  # 生产者类
    def __init__(self, condition, goods, sleeptime=1):  # sleeptime=1
        threading.Thread.__init__(self)
        self.cond = condition
        self.goods = goods
        self.sleeptime = sleeptime

    def run(self):
        cond = self.cond
        goods = self.goods
        for i in range(1000):
            time.sleep(self.sleeptime)
            cond.acquire()
            goods.add()
            print("产品数量:", goods.count, "生产者线程")
            cond.notifyAll()  # 唤醒所有等待的线程,唤醒消费者进程
            cond.release()


class Consumer(threading.Thread):  # 消费者类
    def __init__(self, condition, goods, sleeptime=2):  # sleeptime=2
        threading.Thread.__init__(self)
        self.cond = condition
        self.goods = goods
        self.sleeptime = sleeptime

    def run(self):
        cond = self.cond
        goods = self.goods
        while True:
            cond.acquire()  # 锁住资源
            if goods.empty():  # 如无产品则让线程等待
                cond.wait()
            goods.sub()
            print("产品数量:", goods.count, "消费者线程")
            cond.release()  # 解锁资源


if __name__ == '__main__':
    g = Goods()
    c = threading.Condition()

    list_pro = [Producer(c, g) for _ in range(2)]
    [p.start() for p in list_pro]

    list_pro = [Consumer(c, g) for _ in range(5)]
    [p.start() for p in list_pro]

4、队列queue

线程内的消息队列import queue,进程内的消息队列from multiprocessing import Queue,

import threading
import queue
import time


class jdThread(threading.Thread):
    def __init__(self, index, queue):
        threading.Thread.__init__(self)
        self.index = index
        self.queue = queue

    def run(self):
        while True:
            time.sleep(1)
            item = self.queue.get()
            if item is None:
                break
            print("序号:", self.index, "任务", item, "完成")
            self.queue.task_done()  # task_done方法使得未完成的任务数量-1


if __name__ == '__main__':
    q = queue.Queue(0)
    for i in range(2):
        jdThread(i, q).start()  # 两个线程同时完成任务

    for i in range(10):
        q.put(i)  # put方法使得未完成的任务数量+1

标签:__,UUID,Python,self,threading,线程,import,def
From: https://www.cnblogs.com/q-q56731526/p/17348621.html

相关文章

  • Mac M1芯片无法安装Python3.7的conda环境
    用conda安装python3.7的环境,出现错误(base)➜CodeAnalysisgit:(main)✗condacreate-nCodeAnalysis3.7python=3.7Collectingpackagemetadata(current_repodata.json):doneSolvingenvironment:failedwithrepodatafromcurrent_repodata.json,willretrywit......
  • Python 实时生成曲线的两种方法-Matplotlib/Pyqtgraph
    前言Matplotlib更倾向于制作出版质量的图形,对matlab程序员来说更直观。pyqtgraph不像matplotlib那样完整/成熟,但运行速度要快得多,而且pyqtgraph旨在用于数据采集和分析应用程序,对于python/qt程序员来说更直观。Matplotlib(据我所知)不包括许多pyqtgraph的功能,例如图像......
  • Python环境安装与配置
    Python进行安装:https://www.python.org/如下是针对Windows的下载方式 下载后进行安装,选择自己的安装路径环境配置:script的目录和Python目录添加到path里面 输入python-V 安装配置成功......
  • [oeasy]python0137_相加运算_python之禅_import_this_显式转化
    变量类型相加运算回忆上次内容上次讲了是从键盘输入变量input函数可以有提示字符串需要有具体的变量接收输入的字符串 输入单个变量没有问题但是输入两个变量之后一相加就非常离谱 ​ 添加图片注释,不超过140字(可选)......
  • python发邮件|4-20
    SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。首先,我们来构造一个最简单的纯文本邮件:fromemail.mime.textimportMIMETextmsg=MIMEText('hello......
  • python老男孩第一课
    python 解释器  Cpython 官方标准   --Ipython  --Jython  --PYPY 编程风格   ---缩进统一   -----变量  一般规定(常量大写的  变量  小写的)  ID(变量名)  看变量指向的内存ID   标识符的第一个字符必须是字母表中......
  • python中的字符串和列表
    name="1"name='1'name="""1"""""name='''1'''#都为正确的字符串定义方式#字符串中一个字符占一个空间 #字符串切片格式为[起始:结束:步长]#从起始开始,到结束前一位结束不含结束本身,,默认步长为1,步长可为正可为负a[-4:]#取出a字符串的最后四位#如果只有一......
  • python与c/java的异
    1.注释#为单行注释"""这里是多行注释"""‘’‘这个也可以是多行注释’‘’2.赋值在python中赋值不需要特定变量的类型,并且可以一个等号用于多个赋值,例如name,age,sex="slack",20,"man" 3.输入#输入为函数input()#例1:a=input("请输入内容")#注意in......
  • 【Python】实现按位右移补零操作(同java中的>>>操作)
    答案#Python代码,模拟Java中int型的数的按位右移补零操作defright_shift(val,n):return(val%0x100000000)>>n  逐步推导和解释推论一:对于一个32位的(int型的)二进制,Python中的>>操作等同于Java种的>>>操作证明如下:Python中:binary_value>>n是该二......
  • python结合pandas把excel列转行
    需求,在实际工作中,需要对比两个表格的数据,但是A表格的行和B表格的列做对比,但是由于环境的限制,不能用sql去进行列转行操作,就利用pandas进行一个简单的列转行(没有复合表头)。这种没有多个sheet情况,多个sheet的情况需要切换到需要的sheet内。首先下载pandas,pipinstallpandas 然后......