首页 > 代码库 > Python基础:day10

Python基础:day10

一、python并发编程之多线程

1.1 threading模块

使用方式
from threading import Thread
#!/usr/bin/python
# -*- coding:utf-8 -*-
from threading import Thread
from multiprocessing import  Process

def work(name):
    print(‘%s say hello‘ %name)

if __name__ == ‘__main__‘:
    t=Thread(target=work,args=(‘egon‘,))
    # t=Process(target=work,args=(‘egon‘,))
    t.start()
    print(‘主线程‘)

1.2 开启线程的两种方式(同Process)

#方式一
from threading import Thread
import time
def sayhi(name):
    time.sleep(2)
    print(‘%s say hello‘ %name)

if __name__ == ‘__main__‘:
    t=Thread(target=sayhi,args=(‘egon‘,))
    t.start()
    print(‘主线程‘)

#方式二
from threading import Thread
import time
class Sayhi(Thread):
    def __init__(self,name):
        super().__init__()
        self.name=name
    def run(self):
        time.sleep(2)
        print(‘%s say hello‘ % self.name)


if __name__ == ‘__main__‘:
    t = Sayhi(‘egon‘)
    t.start()
    print(‘主线程‘)

1.3 多进程与多线程的区别

#!/usr/bin/Python
# -*- coding:utf-8 -*-
from threading import Thread
from multiprocessing import Process
import os

def work():
    print(‘hello‘)

if __name__ == ‘__main__‘:
    #在主进程下开启线程
    t=Thread(target=work)
    t.start()
    print(‘主线程/主进程‘)

多线程并发socket 

 

#!/usr/bin/python
# -*- coding:utf-8 -*-
from socket import *
from threading import Thread
def server(ip,port):

    s.bind((ip,port))
    s.listen(5)
    while True:
        conn, addr = s.accept()
        print(‘client‘,addr)
        t = Thread(target=talk, args=(conn, addr))
        t.start()

def talk(conn,addr): #通信
    try:
        while True:
            res=conn.recv(1024)
            if not res:break
            print(‘client %s:%s msg:%s‘ %(addr[0],addr[1],res))
            conn.send(res.upper())
    except Exception:
        pass
    finally:
        conn.close()

if __name__ == ‘__main__‘:
    server(‘127.0.0.1‘, 8080)

 

客户端

 

#_*_coding:utf-8_*_
#!/usr/bin/env python


import socket

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((‘127.0.0.1‘,8080))

while True:
    msg=input(‘>>: ‘).strip()
    if not msg:continue

    s.send(msg.encode(‘utf-8‘))
    data=http://www.mamicode.com/s.recv(1024)>

 

多线程文本保存输入内容

 

#!/usr/bin/python
# -*- coding:utf-8 -*-
from threading import Thread
msg_l=[]
format_l=[]
def talk():
    while True:
        msg=input(‘>>: ‘).strip()
        if not msg:continue
        msg_l.append(msg)

def format():
    while True:
        if msg_l:
            res=msg_l.pop()
            res=res.upper()
            format_l.append(res)

def save():
    while True:
        if format_l:
            res=format_l.pop()
            with open(‘db.txt‘,‘a‘,encoding=‘utf-8‘) as f:
                f.write(‘%s\n‘ %res)

if __name__ == ‘__main__‘:
    t1=Thread(target=talk)
    t2=Thread(target=format)
    t3=Thread(target=save)
    t1.start()
    t2.start()
    t3.start()

 

1.4 线程方法

Thread实例对象的方法
# isAlive(): 返回线程是否活动的。 # getName(): 返回线程名。 # setName(): 设置线程名。 threading模块提供的一些方法: # threading.currentThread(): 返回当前的线程变量。 # threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。 # threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
#!/usr/bin/python
# -*- coding:utf-8 -*-
n=11111111111111111111111111111111111
import time
from threading import Thread
import threading
def work():
    time.sleep(2)
    print(‘%s say hello‘ %(threading.current_thread().getName()))


if __name__ == ‘__main__‘:
    t=Thread(target=work)
    # t.setDaemon(True)#设置守护线程随主线程关闭
    t.start()
    t.join()
    print(threading.enumerate()) #当前活跃的线程对象,是一个列表形式
    print(threading.active_count()) #当前活跃的线程数目
    print(‘主线程‘,threading.current_thread().getName())

  

  

 

  

 

  

 

Python基础:day10