1. 程式人生 > >Python基礎:day10

Python基礎:day10

開啟 exceptio 線程 args [0 brush Coding nco tin

一、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=s.recv(1024)
    print(data)

多線程文本保存輸入內容

#!/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