python-threading


参考

创建线程示例

import threading
from threading import Thread
import time

def test(x):
    print(f'this is {x}')
    time.sleep(1)

def get_thread():
    # 创建十个线程运算test函数
    threads = [Thread(target=test, args=(x, )) for x in [5]*10]
    # 启动线程
    [t.start() for t in threads]
    # 输出线程数量
    print(len(threading.enumerate()))

if __name__ == '__main__':
    get_thread()
# 通过继承类创建线程
import threading
from threading import Thread
import time

# 实现线程类继承自Thread
class MyThread(Thread):
    def __init__(self, x):
        super().__init__()
        self.x = x

    def run(self):
        print(f'this is {self.x}')
        time.sleep(2)

def get_thread():
    # 创建十个线程运算test函数
    threads = [MyThread(x) for x in [5]*10]
    # 启动线程
    [t.start() for t in threads]
    # 输出线程数量
    print(len(threading.enumerate()))

if __name__ == '__main__':
    get_thread()

线程非安全示例

import threading
from threading import Thread
import time

# 线程非安全示例
number = 0
class MyThread1(Thread):

    def run(self):
        global number

        # 此处对全局变量进行1000次加
        for i in range(100000):
            number += 1

class MyThread2(Thread):

    def run(self):
        global number

        # 此处对全局变量进行1000次减
        for i in range(100000):
            number -= 1


if __name__ == '__main__':
    # 创建线程
    threads1 = MyThread1()
    threads2 = MyThread2()
    threads1.start()
    threads2.start()
    # 按照逻辑应该输出0,但多次运行后会出现非0,因为两个线程同时对全局变量进行修改造成的
    print(number)

线程安全示例

import threading
from threading import Thread
import time

# 线程非安全示例
number = 0
# 创建线程锁
lock = threading.Lock()

class MyThread1(Thread):

    def run(self):
        global number, lock

        # 此处对全局变量进行1000次加
        for i in range(1000000):
            # 锁住
            locked = lock.acquire()
            if locked:  # 如果获取了锁就进行操作,操作完后释放锁
                number += 1
                lock.release()


class MyThread2(Thread):

    def run(self):
        global number, lock

        # 此处对全局变量进行1000次减
        for i in range(1000000):
            # 锁住
            locked = lock.acquire()
            if locked:  # 如果获取了锁就进行操作,操作完后释放锁
                number -= 1
                lock.release()

if __name__ == '__main__':
    # 创建线程
    threads1 = MyThread1()
    threads2 = MyThread2()
    threads1.start()
    threads2.start()
    threads1.join()# 等待线程结束再往下走
    threads2.join()
    # 按照逻辑应该输出0,但多次运行后会出现非0,因为两个线程同时对全局变量进行修改造成的
    print(number)

死锁

  • 使用多个锁时候会出现死锁,避免方法是不使用多个锁或设置死锁超时等待
import threading
from threading import Thread

number = 100
mutex1 = threading.Lock() # 创建锁对象
mutex2 = threading.Lock()

class MyThread1(Thread):

    def run(self):
        global number
        for i in range(1000):
            if mutex1.acquire(): # 拿到锁就执行下面
                number += 1
                if mutex2.acquire():
                    print('this is mutex2')
                    mutex2.release()
                mutex1.release() # 释放锁
        print(number)
class MyThread2(Thread):

    def run(self):
        global number
        for i in range(1000):
            if mutex2.acquire(): # 拿到锁就执行下面
                number += 1
                if mutex1.acquire():
                    print('this is mutex2')
                    mutex1.release()
                mutex2.release() # 释放锁
        print(number)

def get_thread1():
    l_thread = (MyThread1(), MyThread2())
    for t in l_thread:
        t.start()

if __name__ == '__main__':
    get_thread1()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值