socket网络编程多线程

本文通过多个示例详细介绍了Python中多线程的应用,包括基本的多线程创建、线程间的等待与通信、后台线程管理、锁与资源同步、条件变量的使用以及信号量等高级主题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/env python
#-*-coding:utf-8-*-
#多进程
import threading
import time
def thfun():
    s=0
    for i in range(30):
        s+=i
        time.sleep(0.1)
    print(s)

class MyThread(threading.Thread):
    def run(self):
        s=0
        for i in range(30):
            s+=i
            time.sleep(0.1)
        print(s)


if __name__=='__main__':
    #ths=[threading.Thread(target=thfun) for i in range(2)]
    ths=[MyThread() for i in range(2)]
    for th in ths:
       th.start()
    #!/usr/bin/env python
#-*-coding:utf-8-*-
#线程间等待 join 线程等待
import threading,time

class MyThread(threading.Thread):
    def run(self):
        for i in range(30):
            print('threading:',i)
            time.sleep(0.1)

if __name__=='__main__':
    t=MyThread()
    t.start()
    #制定超时1s
    #t.join(1)
    t.join()
    for i in range(10):
        print('Main:',i)
        time.sleep(0.1)
#!/usr/bin/env python
#-*-coding:utf-8-*-
#后台线程 daemon
#后台线程不会结束

import threading,time

def dmn():
    print('dmn start...')
    time.sleep(2)
    print('dmn end.')

def ndmn():
    print('ndmn start...')
    time.sleep(1)
    print('ndmn end.')


d=threading.Thread(target=dmn)
#后台线程
d.daemon=True
n=threading.Thread(target=ndmn)

print('start...')
d.start()
n.start()
print('end...')

#!/usr/bin/env python
#-*-coding:utf-8-*-
#线程等待,指令锁 可重入锁,acquire(blocking=True,timeout=-1) release() threading.RLock
import threading,time,random


share=4


class MyThread(threading.Thread):
    def __init__(self,i):
        super().__init__()
        self.i=i

    def run(self):
        global share 
        for d in range(3):
            lock.acquire()
            print(share)
            share+=self.i
            time.sleep(random.random())
            print('+',self.i,'=',share)
            lock.release()

lock=threading.Lock()

if __name__=='__main__':
    t=MyThread(2)
    tt=MyThread(6)
    t.start()
    tt.start()


#!/usr/bin/env python
#-*-coding:utf-8-*-
#条件变量 生产者,消费者
import threading,time

share=0

share_cond=threading.Condition()

class ProThread(threading.Thread):
    def __init__(self):
        super().__init__()
        self.name='Produce'

    def run(self):
        global share
        if share_cond.acquire():
            while True:
                if not share:
                    share+=1
                    print(self.name,share)
                    #唤醒需要本资源的线程
                    share_cond.notify()
                share_cond.wait()
                time.sleep(1)

#消费者
class CustomThread(threading.Thread):
    def __init__(self):
        super().__init__()
        self.name="Custom"

    def run(self):
        global share
        if share_cond.acquire():
            while True:
                if share:
                    share-=1
                    print(self.name,share)
                    share_cond.notify()
                share_cond.wait()
                time.sleep(1)
if __name__=='__main__':
    t=ProThread()
    tt=CustomThread()
    t.start()
    tt.start()
    
#!/usr/bin/env python
#-*-coding:utf-8-*-
#线程同步,信号量
import threading, time

sema=threading.Semaphore(2)
#资源的个数

class MyThread(threading.Thread):
    def __init__(self,name):
        super().__init__()
        self.name=name

    def run(self):
        #获得一个资源
        if sema.acquire():
            print(self.name,'Had got resource.')
            time.sleep(1)
        sema.release()
        print(self.name,'Had released resource.')
if __name__=='__main__':
    ths=[MyThread(str(i)+'Sema') for i in range(5)]

    for th in ths:
        th.start()
#!/usr/bin/env python
#-*-coding:utf-8-*-
#等待线程 ,线程通信
#定时执行 threading.Timer threading.Timer(3,start)

import threading
import time


event=threading.Event()

#等待线程
class MyThreadWait(threading.Thread):
    def run(self):
        self.name='Wait Thread'
        print(self.name,'Wait...')
        event.wait()#等到内部标记为True
        print(self.name,'Start...')
        event.clear()

class MyThreadMain(threading.Thread):
    def run(self):
        time.sleep(3)
        print('Main thread set event flag!')
        event.set()
        #内部标记为空

if __name__=='__main__':
    thw=MyThreadWait()
    thm=MyThreadMain()
    thw.start()
    thm.start()






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值