zoukankan      html  css  js  c++  java
  • 多线程

    进程只是用来把资源集中到一起(进程只是一个资源单位,或者说资源集合),而线程才是cpu上的执行单位

    进程之间是竞争关系,线程之间是协作关系

    为何要用多线程

    多线程指的是,在一个进程中开启多个线程,简单的讲,如果多个任务共用一块地址空间,name必须在一个进程内开启多个线程,详细的讲分为4点:

    1.多线程共享一个进程的地址空间

    2.线程闭进程更轻量级,线程比进程更容易创建和撤销,在许多的操作系统中,创建一个线程比创建一个进程要快10到100倍,在有大量线程需要动态和修改时,这一特性很有用

    3.若多个线程都是cpu密集型的,那么并不能获得性能上的增强,但是如果存在大量的计算机和大量的io处理,拥有多个线程允许这些活动彼此重叠运行,从而会加快程序的执行速度

    4.在多cpu中,为了最大限度的利用多核,可以开启多个线程,比开进程开销要小得多(这一条python不适用)

    开启线程的两种方式:

    from threading import Thread

    import time

    def sayhi(name):

      time.sleep(2)

      print(name)

    if __name__=='__main__':

      t=Thread(target=sayhi,args=('egon',))

      t.start()

      print('主线程')

    from threading import Tread

    import time

    class sayhi(Thread):

      def __init__(self,name):

        super().__init__()

        self.name=name

      def run(self):

      time.sleep(2)

      print(self.name)

    if __name__=='__main__':

      t=sayhi('egon')

      t.start()

      print('主线程')

    在一个进程下开启多个线程与在一个进程下开启多个子进程的区别

    开启多个线程的速度要快

    from threading import Thread

    from multiprocessing import Process

    import os

    def work():

      print('hellow')

    if  __name__=='__main__':

      #在进程下开启线程

      t=Thread(target=work)

      t.start()

      print('主进程/主线程',os.getpid())

      #在主进程下开启子进程

      t=Process(target=work)

      t.start()

      print('主线程/主进程',os.getpid())

    同一进程内的线程之间共享进程内的数据

    进程与进程之间数据隔离

    多线程并发socket服务端

    from threading import Thread

    from multiprocessing import Process

    from socket import *

    s=socket(AF_INET,SOCK_STREAM)

    s.bind(('127.0.0.1',8080))

    s.listen(5)

    def action(conn):

      while True:

        data=conn.recv(1024)

        print(data)

        conn.send(data.upper())

    if __name__=='__main__':

      while True:

      conn.addr=s.accept()

      p=Tread(target=action,args=(aonn,))

      p.start()

    客户端

    from socket import *

    s=socket(AF_INET,SOCK_STREAM)

    s.connect(('127.0.0.1',8080))

    while True:

      inp=input('请输入')

      if not inp:

        continue

      s.send(inp.encode('utf-8'))

      data=s.recv(1024)

      print(data.decode('utf-8'))

    线程相关的其他方法

    Thread实例化对象的方法

    isAlive():返回线程是否活动的

    getName():返回线程名

    setName():设置线程名

    threading模块提供的一些方法

    threading.currentThread():返回当前的线程变量

    threading.enumerate():返回正在运行的线程list,正在运行指线程启动后,结束前,

    不包括启动前终止后的线程

    threading.activeCount():返回正在运行的线程数量,与len(threading.enumerate())有相同的结果

    主线程等待子线程结束

    from threading import Thread

    import time 

    def sayhi(name):

      time.sleep(2)

      print(name)

    if __name__=='__main__':

      t=Thread(target=sayhi,args=('egon'))

      t.start()

      t.join()

      print('主线程')

      print(t.is_alive())

    守护线程

    无论是进程还是线程,都遵循:守护xxx会等待主xxx运行完毕后被销毁

    需要强调的是:运行完毕并非终止运行

    1.对主进程来说,运行完毕时主进程代码运行完毕

    2.对主线程来说,运行完毕时主线程所在的进程内所有非守护线程全部运行完毕,主线程才算完毕

  • 相关阅读:
    UVA 1386 Cellular Automaton
    ZOJ 3331 Process the Tasks
    CodeForces 650B Image Preview
    CodeForces 650A Watchmen
    CodeForces 651B Beautiful Paintings
    CodeForces 651A Joysticks
    HUST 1601 Shepherd
    HUST 1602 Substring
    HUST 1600 Lucky Numbers
    POJ 3991 Seinfeld
  • 原文地址:https://www.cnblogs.com/fushaunglin/p/9601099.html
Copyright © 2011-2022 走看看