Python threading多线程

£神魔★判官ぃ 2023-06-10 10:25 24阅读 0赞

目录

1、

2、Lock


1、

  1. # encoding: utf-8
  2. import threading
  3. import time
  4. from queue import Queue
  5. def thread_1_job():
  6. print("Thread-1 start\n")
  7. for i in range(10):
  8. time.sleep(0.3)
  9. print("Thread-1 finished\n")
  10. def thread_2_job():
  11. print("Thread-2 start\n")
  12. for c in "ABCDEFG":
  13. time.sleep(0.3)
  14. print("Thread-2 finished\n")
  15. def queue_job(list,q):
  16. for i in range(len(list)):
  17. list[i] = list[i] **2
  18. q.put(list)
  19. """threading多线程的常用方法"""
  20. def main_1():
  21. # 添加一个线程,并添加线程所需函数
  22. thread = threading.Thread(target=thread_1_job)
  23. # 运行线程
  24. thread.start()
  25. # 当前激活的线程数
  26. print(threading.active_count())
  27. # 当前激活线程的详细信息
  28. print(threading.enumerate())
  29. # 正在运行的线程详细信息
  30. print(threading.current_thread())
  31. """join主线程等待线程执行完毕"""
  32. def main_join():
  33. # 添加一个线程,并添加线程所需函数
  34. # target= thread_job()不能带括号
  35. thread_1 = threading.Thread(target=thread_1_job,name='Thread-1')
  36. thread_2 = threading.Thread(target=thread_2_job,name="Thread-2")
  37. thread_1.start()
  38. thread_2.start()
  39. # 等待线程运行结束后在去继续向后执行
  40. thread_1.join()
  41. thread_2.join()
  42. print("all threads is done !!")
  43. """queue多线程分批处理数据"""
  44. def main_queue(data):
  45. # 存放线程的返回值
  46. q = Queue()
  47. threads = []
  48. #
  49. for i in range(4):
  50. # queue_job没有括号,args是向线程传递的参数
  51. t = threading.Thread(target=queue_job,args=(data[i],q))
  52. t.start()
  53. threads.append(t)
  54. for t in threads:
  55. t.join()
  56. result = []
  57. for _ in range(4):
  58. # 该方法只能拿出一个值,并且有序
  59. r = q.get()
  60. result.append(r)
  61. print(result)
  62. if __name__ == '__main__':
  63. # main_1()
  64. # main_join()
  65. data = [[1,2,3],[3,4,5],[4,4,4],[5,5,5]]
  66. main_queue(data)

2、Lock

  1. # encoding: utf-8
  2. import threading
  3. import time
  4. from queue import Queue
  5. """处理共享变量"""
  6. def job1():
  7. global A,lock
  8. # 开始加锁
  9. lock.acquire()
  10. for i in range(2):
  11. A += 1
  12. print("job_1 num = %s " % A)
  13. # 释放锁
  14. lock.release()
  15. def job2():
  16. global A,lock
  17. # 开始加锁
  18. lock.acquire()
  19. for i in range(2):
  20. A += 10
  21. print("job_2 num =%s " % A)
  22. # 释放锁
  23. lock.release()
  24. if __name__ == '__main__':
  25. """实现将job1 打印完后再打印 job2"""
  26. A = 0 # 全局变量
  27. lock = threading.Lock()
  28. t1 = threading.Thread(target=job1)
  29. t2 = threading.Thread(target=job2)
  30. t1.start()
  31. t2.start()
  32. t1.join()
  33. t2.join()

发表评论

表情:
评论列表 (有 0 条评论,24人围观)

还没有评论,来说两句吧...

相关阅读

    相关 线Thread

    -------------------- \\java中的线程分类 User Thread 用户线程 运行在前台,执行具体任务: 比如程序的主线程、连接网络的子线程等等