20 python

线程:进程中一个单一连续控制流程

一个程序至少有一个进程 一个进程至少有一个线程

  1 import threading
  2 import time
  3 
  4 def say():
  5     print("hello")
  6     time.sleep(1)
  7 for i in range(5):
  8     t = threading.Thread(target = say)

  9     t.start()

x线程的子类

  1 import threading
  2 import time
  3 
  4 class MyThread(threading.Thread):
  5     def run(self):
  6         for i in range(3):          
  7             time.sleep(1)
  8             print("I am "+ self.name + "@" + str(i))
  9 
 10 
 11 t = MyThread()
 12 t.start()
 13 t1 = MyThread()

 14 t1.start()

线程共享全局变量

线程同步 互斥锁Lock

mutex = threading.Lock()

mutex.acquire(blocking) 加锁 参数 是否阻塞

mutex.release()解锁

  1 import threading
  2 g_num = 0
  3 mutex = threading.Lock()
  4 def worker():
  5     for i in range(2000000):
  6         mutex.acquire(True)
  7         global g_num
  8         g_num+=1
  9         mutex.release()
 10 tl = [] 
 11 for i in range(2):
 12     t = threading.Thread(target=worker)
 13     t.start()
 14     tl.append(t)
 15 for i in tl:
 16     i.join()
 17 print("g_num:%d"%g_num)

运用队列进行线程间通讯:

    Queue实现了锁原语

  1 import threading
  2 import time
  3 from queue import Queue
  4 
  5 queue = Queue()
  6 
  7 class Producer(threading.Thread):
  8     def run(self):
  9         global queue
 10         while True:
 11             if queue.qsize() < 100:
 12                 for i in range(100):
 13                     msg = "产品" + str(i)
 14                     queue.put(msg)
 15                     print("product %s"%msg)
 16             time.sleep(1)
 17 
 18 class Consumer(threading.Thread):
 19     def run(self):
 20         global queue
 21         while True:
 22             if queue.qsize()>10:
 23                 for i in range(3):
 24                     msg = queue.get()
 25                     print("consum %s"%msg)
 26             time.sleep(0.5)
 27 
 28 p = Producer()
 29 c = Consumer()
 30 p.start()
 31 c.start()
 32 
 33 p.join()
 34 c.join()

ThreadLocal 变量

一个ThreadLocal变量虽然是全局变量 但每个线程都智能读写自己线程的独立副本 互不干扰

  1 import threading
  2 
  3 localSchool = threading.local()
  4 
  5 def process_student():
  6     name = localSchool.student
  7     print("hello %s in %s"%(name, threading.current_thread().name))
  8 
  9 def process_thread(name):
 10         localSchool.student = name
 11         process_student()
 12 
 13 t1 = threading.Thread(target=process_thread, args=("zhangsan",), name="t1")
 14 t2 = threading.Thread(target=process_thread, args=("lisi",), name="t2")
 15 
 16 t1.start()
 17 t2.start()
 18 t1.join()
 19 t2.join()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值