python线程学习笔记

本文详细介绍了Python线程的创建,包括函数和类两种方式,并探讨了线程的方法如start()和join()。此外,文章还讲解了线程锁的重要性,包括Lock和RLock的使用,以及如何通过信号量实现线程同步。最后,提到了Python多线程在IO操作密集型任务中的优势和队列queue在多线程中的线程安全应用。
摘要由CSDN通过智能技术生成

1.线程创建   

1.1函数创建线程

def helloworld():

    time.sleep(2)
    print("hello world")

t = threading.Thread(target=helloworld)
t.start()
print("main thread")

1.2类创建线程

class HelloWorld(threading.Thread):
    def __init__(self,id):
        self.id = id
        super(HelloWorld,self).__init__()

    def run(self):
        time.sleep(2)
        print("thread %d helloworld" % self.id)

for i in range(5):
    t = HelloWorld(i)
    t.start()
print("main thread")

2.线程的方法

t.start()  启动线程活动

t.join()  保证当前线程执行完成以后,再执行其他线程。

import threading,time

count = 0

def adder():
    global count
    count = count + 1
    time.sleep(0.1)
    count = count + 1

threads = []
for i in range(100):
    thread = threading.Thread(target=adder)
    thread.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值