zoukankan      html  css  js  c++  java
  • 线程

    什么是线程:

      线程依赖于进程,是真正执行代码的单位。

    线程与进程的关系:

      1.进程是资源单位,而线程是进程单位里的执行单位。  

      2.一个进程至少含有一个线程,但一个线程只能隶属于一个进程,且同一个进程中的线程可以共享资源。

    并行的概念:

      对于有多核的cpu,一个进程中的多个线程可以分别交给不同的CPU同时执行进程中的线程。

    并发的概念:

      对于有多核的cpu,一个进程内的多个线程只能交给一个cpu执行,利用cpu的快速切换使多个线程的执行

    Python的多线程:

      由于GIL导致同一时刻,同一进程内的多个线程,只能有一个线程被运行。因此,Python的多线程只支持并发,多进程支持并行。

    需要使用的模块:

    1 from  threading

    模块需要掌握的方法:

      join()、start()

    线程的开启:

    import   threading,time
    def  music():
        print('music')
        time.sleep(3)
    def  xieboke():
        print('xieboke')
        time.sleep(3)
    if __name__ == '__main__':
        start_time = time.time()
        t1 = threading.Thread(target=music,)
        t2 = threading.Thread(target=xieboke,)
        t1.start()
        t2.start()
        print('end')
    线程的开启

    线程池:

     1 from   concurrent.futures  import   ThreadPoolExecutor
     2 from   threading import  current_thread
     3 import time,random
     4 def  task(n):
     5     print('%s is running'%current_thread().getName())
     6     time.sleep(random.randint(1,4))
     7     return n**2
     8 if __name__ == '__main__':
     9     t = ThreadPoolExecutor(3)#默认是cup的核数*5
    10     objs=[]
    11     for i in range(10):
    12         obj = t.submit(task,i)
    13         objs.append(obj)
    14     t.shutdown(wait=True,)
    15     for obj in objs:
    16         print(obj.result())
    17     print('主线程',current_thread().getName())
    线程池
  • 相关阅读:
    hdu 5723 Abandoned country 最小生成树 期望
    OpenJ_POJ C16G Challenge Your Template 迪杰斯特拉
    OpenJ_POJ C16D Extracurricular Sports 打表找规律
    OpenJ_POJ C16B Robot Game 打表找规律
    CCCC 成都信息工程大学游记
    UVALive 6893 The Big Painting hash
    UVALive 6889 City Park 并查集
    UVALive 6888 Ricochet Robots bfs
    UVALive 6886 Golf Bot FFT
    UVALive 6885 Flowery Trails 最短路
  • 原文地址:https://www.cnblogs.com/liuyinzhou/p/7966987.html
Copyright © 2011-2022 走看看