• python之线程


    什么是线程?

    开启线程的两种方式

    方式一:

     1 import time
     2 import random
     3 from threading import Thread
     4 
     5 
     6 def eat(name):
     7     print('{} is eating'.format(name))
     8     time.sleep(random.randrange(1, 5))
     9     print('{} has gone'.format(name))
    10 
    11 
    12 if __name__ == "__main__":
    13     t1 = Thread(target=eat, args=('james', ))
    14     t1.start()
    15     print('
    主线程')

    方式二:

     1 import time
     2 import random
     3 from threading import Thread
     4 
     5 
     6 class MyThread(Thread):
     7     def __init__(self, name):
     8         super().__init__()
     9         self.name = name
    10 
    11     def run(self):
    12         print('{} is eating'.format(self.name))
    13         time.sleep(random.randrange(1, 5))
    14         print('{} has gone'.format(self.name))
    15 
    16 
    17 if __name__ == "__main__":
    18     t1 = MyThread('james')
    19     t1.start()
    20     print('
    主线程')

    进程与线程之间的区别

    • 开进程的开销远大于开线程
    • 同一进程内的多个线程共享进程的地址空间
    • 同一个进程下的线程的pid是一样的

    线程的常见属性和方法

    获取线程名称

     1 import time
     2 import random
     3 from threading import Thread, current_thread
     4 from multiprocessing import Process, current_process
     5 
     6 
     7 class MyThread(Thread):
     8     def __init__(self, name):
     9         super().__init__()
    10         self.name = name
    11 
    12     def run(self):
    13         print('{} is eating'.format(self.name))
    14         time.sleep(random.randrange(1, 5))
    15         print(current_thread().getName())
    16         print('{} has gone'.format(self.name))
    17 
    18 
    19 if __name__ == "__main__":
    20     t1 = MyThread('james')
    21     t1.start()
    22     print('
    主线程', current_thread().getName())

     互斥锁

     1 from threading import Thread, Lock
     2 import time
     3 
     4 n = 100
     5 
     6 def task():
     7     global n
     8     mutex.acquire()
     9     temp = n
    10     time.sleep(0.1)
    11     n = temp - 1
    12     mutex.release()
    13 
    14 
    15 if __name__ == "__main__":
    16     mutex = Lock()
    17     t_l = []
    18     for i in range(100):
    19         t = Thread(target=task)
    20         t_l.append(t)
    21         t.start()
    22 
    23     for t in t_l:
    24         t.join()
    25 
    26     print('', n)

    将并发的过程变为串行的过程

  • 相关阅读:
    Offer快到碗里来,囊中之物-CAS
    SQL 两表一对多关联,主表某字段保存所有关联的id
    No Feign Client for loadBalancing defined
    Clean Code读书笔记 3--类
    Clean Code读书笔记(2)---函数
    Clean Code读书笔记(1)---有意义的命名
    [CF1354D] Multiset
    [CF1365E] Maximum Subsequence Value
    [CF1358D] The Best Vacation
    [CF463C] Gargari and Bishops
  • 原文地址:https://www.cnblogs.com/xiebinbbb/p/13968228.html
Copyright © 2020-2023  润新知