Hướng dẫn what is multi thread in python - đa luồng trong python là gì

Bài viết này bao gồm những điều cơ bản của đa luồng trong ngôn ngữ lập trình Python. Giống như đa xử lý, đa luồng là một cách để đạt được đa nhiệm. Trong đa luồng, khái niệm về chủ đề được sử dụng. Trước tiên chúng ta hãy hiểu khái niệm về chủ đề trong kiến ​​trúc máy tính.threads is used. Let us first understand the concept of thread in computer architecture.

Chủ đề

Trong điện toán, một quy trình là một ví dụ của một chương trình máy tính đang được thực thi. Bất kỳ quá trình nào cũng có 3 thành phần cơ bản:process is an instance of a computer program that is being executed. Any process has 3 basic components:

  • Một chương trình thực thi.
  • Dữ liệu liên quan cần thiết cho chương trình (biến, không gian làm việc, bộ đệm, v.v.)
  • Bối cảnh thực hiện của chương trình (trạng thái của quá trình)

Một luồng là một thực thể trong một quy trình có thể được lên lịch để thực hiện. Ngoài ra, đây là đơn vị xử lý nhỏ nhất có thể được thực hiện trong hệ điều hành (hệ điều hành). Nói một cách đơn giản, một luồng là một chuỗi các hướng dẫn như vậy trong một chương trình có thể được thực thi độc lập với mã khác. Để đơn giản, bạn có thể cho rằng một chủ đề chỉ đơn giản là một tập hợp con của một quá trình! Một luồng chứa tất cả thông tin này trong khối điều khiển luồng (TCB):thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an OS (Operating System). In simple words, a thread is a sequence of such instructions within a program that can be executed independently of other code. For simplicity, you can assume that a thread is simply a subset of a process! A thread contains all this information in a Thread Control Block (TCB):

  • Định danh luồng: ID duy nhất (TID) được gán cho mọi luồng mới Unique id (TID) is assigned to every new thread
  • Con trỏ Stack: Chỉ vào ngăn xếp của chủ đề trong quá trình. Ngăn xếp chứa các biến cục bộ trong phạm vi luồng. Points to thread’s stack in the process. Stack contains the local variables under thread’s scope.
  • Bộ đếm chương trình: Một đăng ký lưu trữ địa chỉ của hướng dẫn hiện đang được thực hiện theo luồng. a register which stores the address of the instruction currently being executed by thread.
  • Trạng thái chủ đề: Có thể chạy, sẵn sàng, chờ đợi, bắt đầu hoặc thực hiện. can be running, ready, waiting, start or done.
  • Bộ đăng ký chủ đề Bộ đăng ký: Các thanh ghi được gán cho luồng cho các tính toán. registers assigned to thread for computations.
  • Con trỏ quy trình cha mẹ: Một con trỏ tới khối điều khiển quá trình (PCB) của quá trình mà luồng tồn tại. A pointer to the Process control block (PCB) of the process that the thread lives on.

Hãy xem xét sơ đồ dưới đây để hiểu mối quan hệ giữa quy trình và luồng của nó:

Hướng dẫn what is multi thread in python - đa luồng trong python là gì

Đa luồng: Nhiều luồng có thể tồn tại trong một quá trình trong đó:Multiple threads can exist within one process where:

  • Mỗi luồng chứa bộ thanh ghi riêng và các biến cục bộ (được lưu trữ trong ngăn xếp).register set and local variables (stored in stack).
  • Tất cả các luồng của một quy trình chia sẻ các biến toàn cầu (được lưu trữ trong heap) và mã chương trình.global variables (stored in heap) and the program code.

Hãy xem xét sơ đồ dưới đây để hiểu làm thế nào nhiều luồng tồn tại trong bộ nhớ:

Hướng dẫn what is multi thread in python - đa luồng trong python là gì

MultiThreading được định nghĩa là khả năng của bộ xử lý để thực hiện đồng thời nhiều luồng. is defined as the ability of a processor to execute multiple threads concurrently.

Trong một CPU đơn giản, một lõi, nó đạt được bằng cách sử dụng chuyển đổi thường xuyên giữa các luồng. Điều này được gọi là chuyển đổi ngữ cảnh. Trong chuyển đổi ngữ cảnh, trạng thái của một luồng được lưu và trạng thái của một luồng khác được tải bất cứ khi nào ngắt (do I/O hoặc được đặt thủ công) diễn ra. Chuyển đổi ngữ cảnh diễn ra thường xuyên đến mức tất cả các luồng dường như đang chạy tương đồng (điều này được gọi là đa nhiệm).context switching. In context switching, the state of a thread is saved and state of another thread is loaded whenever any interrupt (due to I/O or manually set) takes place. Context switching takes place so frequently that all the threads appear to be running parallelly (this is termed as multitasking).

Hướng dẫn what is multi thread in python - đa luồng trong python là gì

Hãy xem xét sơ đồ dưới đây trong đó một quy trình chứa hai luồng hoạt động: & nbsp;

Đa luồng trong Python

Trong Python, mô -đun luồng cung cấp API rất đơn giản và trực quan để sinh ra nhiều luồng trong một chương trình. Chúng ta hãy xem xét một ví dụ đơn giản bằng cách sử dụng mô -đun luồng: & nbsp;threading module provides a very simple and intuitive API for spawning multiple threads in a program. Let us consider a simple example using a threading module: 

Python3

import threading

import threading
0
import threading
1

import threading
2
import threading
3
import threading
4
import threading
5

import threading
0
t1.start()
t2.start()
4

import threading
2
import threading
3
import threading
4
t1.start()
t2.start()
8
import threading
6
import threading
7
import threading
8
import threading
9
t1.start()
t2.start()
2

t1.join()
t2.join()
4
t1.join()
t2.join()
5
t1.join()
t2.join()
6
t1.join()
t2.join()
6
t1.join()
t2.join()
8
t1.join()
t2.join()
9

import threading
2
ID of process running main program: 11758
Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758
1
t1.join()
t2.join()
6
ID of process running main program: 11758
Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758
3
t1.join()
t2.join()
6
ID of process running main program: 11758
Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758
5
t1.join()
t2.join()
6
import threading
4
ID of process running main program: 11758
Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758
8
ID of process running main program: 11758
Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758
9

import threading
2
print("ID of process running main program: {}".format(os.getpid()))
1
t1.join()
t2.join()
6
ID of process running main program: 11758
Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758
3
t1.join()
t2.join()
6
print("ID of process running main program: {}".format(os.getpid()))
5
t1.join()
t2.join()
6
import threading
4
ID of process running main program: 11758
Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758
8
ID of process running main program: 11758
Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758
9

import threading
2
print("Main thread name: {}".format(threading.main_thread().name))
1

import threading
2
print("Main thread name: {}".format(threading.main_thread().name))
3

import threading
2
print("Main thread name: {}".format(threading.main_thread().name))
5

import threading
2
print("Main thread name: {}".format(threading.main_thread().name))
7

import threading
2
import threading
3
import threading
4
print("Task 1 assigned to thread: {}".format(threading.current_thread().name))
1
print("Task 1 assigned to thread: {}".format(threading.current_thread().name))
2

Square: 100
Cube: 1000
Done!

Hãy để chúng tôi cố gắng hiểu mã trên:

  • Để nhập mô -đun luồng, chúng tôi làm:
import threading
  • Để tạo một luồng mới, chúng tôi tạo một đối tượng của lớp luồng. Nó có những lập luận sau:Thread class. It takes following arguments:
    • Mục tiêu: Hàm được thực thi theo luồng: the function to be executed by thread
    • args: Các đối số được chuyển đến hàm đích: the arguments to be passed to the target function
  • Để bắt đầu một luồng, chúng tôi sử dụng phương thức bắt đầu của lớp luồng.start method of Thread class.
t1.start()
t2.start()
  • Khi các luồng bắt đầu, chương trình hiện tại (bạn có thể nghĩ về nó giống như một luồng chính) cũng tiếp tục thực hiện. Để dừng thực hiện chương trình hiện tại cho đến khi hoàn tất, chúng tôi sử dụng phương thức tham gia.join method.
t1.join()
t2.join()
  • Do đó, chương trình hiện tại trước tiên sẽ chờ đợi hoàn thành T1 và sau đó là T2. Một khi, chúng được hoàn thành, các tuyên bố còn lại của chương trình hiện tại được thực thi.t1 and then t2. Once, they are finished, the remaining statements of current program are executed.

Hãy xem xét sơ đồ dưới đây để hiểu rõ hơn về cách thức hoạt động của chương trình: & NBSP;

Hướng dẫn what is multi thread in python - đa luồng trong python là gì

Hãy xem xét chương trình Python được đưa ra dưới đây, trong đó chúng tôi in tên luồng và quy trình tương ứng cho từng nhiệm vụ: & nbsp;

Python3

import threading

import threading
0
import threading
1

import threading
2
import threading
3
import threading
4
import threading
5

import threading
0
t1.start()
t2.start()
4

import threading
2
import threading
3
import threading
4
t1.start()
t2.start()
8
import threading
6
import threading
7
import threading
8
import threading
9
t1.start()
t2.start()
2

import threading
0 threading6

import threading
2
import threading
3import1
import threading
00 import3
import threading
7import5

import threading
2
import threading
3import8___

t1.join()
t2.join()
4
t1.join()
t2.join()
5
t1.join()
t2.join()
6
t1.join()
t2.join()
6
import threading
17

import threading
2
import threading
3import8import9
import threading
222__17

import threading
2
import threading
3
import threading
27
import threading
7import5

import threading
2
ID of process running main program: 11758
Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758
1
t1.join()
t2.join()
6
ID of process running main program: 11758
Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758
3
t1.join()
t2.join()
6
import threading
35
t1.join()
t2.join()
6
import threading
37
print("Task 1 assigned to thread: {}".format(threading.current_thread().name))
2

import threading
2
print("ID of process running main program: {}".format(os.getpid()))
1
t1.join()
t2.join()
6
ID of process running main program: 11758
Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758
3
t1.join()
t2.join()
6__

import threading
2
print("Main thread name: {}".format(threading.main_thread().name))
1

import threading
2
print("Main thread name: {}".format(threading.main_thread().name))
3

import threading
2
print("Main thread name: {}".format(threading.main_thread().name))
5

import threading
2
print("Main thread name: {}".format(threading.main_thread().name))
7

ID of process running main program: 11758
Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 11758
Task 2 assigned to thread: t2
ID of process running task 2: 11758

Hãy để chúng tôi cố gắng hiểu mã trên:

  • Chúng tôi sử dụng hàm Os.getPid () để có ID của quy trình hiện tại.os.getpid() function to get ID of current process.
print("ID of process running main program: {}".format(os.getpid()))
  • Như rõ ràng từ đầu ra, ID quy trình vẫn giữ nguyên cho tất cả các luồng.
  • Chúng tôi sử dụng chức năng Threading.main_Thread () để lấy đối tượng luồng chính. Trong điều kiện bình thường, luồng chính là luồng mà người phiên dịch Python đã được bắt đầu. thuộc tính tên của đối tượng luồng được sử dụng để lấy tên của luồng.threading.main_thread() function to get the main thread object. In normal conditions, the main thread is the thread from which the Python interpreter was started. name attribute of thread object is used to get the name of thread.
print("Main thread name: {}".format(threading.main_thread().name))
  • Chúng tôi sử dụng chức năng renthing.civerse_thread () để lấy đối tượng luồng hiện tại.threading.current_thread() function to get the current thread object.
print("Task 1 assigned to thread: {}".format(threading.current_thread().name))

Sơ đồ được đưa ra dưới đây xóa khái niệm trên:

Hướng dẫn what is multi thread in python - đa luồng trong python là gì

Vì vậy, đây là một giới thiệu ngắn gọn về đa luồng trong Python. Bài viết tiếp theo trong loạt bài này bao gồm đồng bộ hóa giữa nhiều luồng. MultiThreading trong Python | Đặt 2 (đồng bộ hóa) & nbsp;synchronization between multiple threads. Multithreading in Python | Set 2 (Synchronization) 

Bài viết này được đóng góp bởi Nikhil Kumar. Nếu bạn thích GeekSforGeeks và muốn đóng góp, bạn cũng có thể viết một bài viết bằng Write.GeekSforGeek.org hoặc gửi bài viết của bạn. Xem bài viết của bạn xuất hiện trên trang chính của GeekSforGeek và giúp các chuyên viên máy tính khác.Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.

Vui lòng viết nhận xét nếu bạn tìm thấy bất cứ điều gì không chính xác, hoặc bạn muốn chia sẻ thêm thông tin về chủ đề được thảo luận ở trên.


Nhiều chủ đề trong Python là gì?

MultiThreading đề cập đến việc thực hiện đồng thời nhiều luồng bằng cách nhanh chóng chuyển đổi điều khiển CPU giữa các luồng (được gọi là chuyển đổi ngữ cảnh). Khóa thông dịch viên toàn cầu Python giới hạn một luồng để chạy tại một thời điểm ngay cả khi máy chứa nhiều bộ xử lý.concurrently executing multiple threads by rapidly switching the control of the CPU between threads (called context switching). The Python Global Interpreter Lock limits one thread to run at a time even if the machine contains multiple processors.​

Đa chủ đề được sử dụng để làm gì?

MultiThreading là khả năng của một chương trình hoặc hệ điều hành để kích hoạt nhiều người dùng cùng một lúc mà không yêu cầu nhiều bản sao của chương trình chạy trên máy tính.MultiThreading cũng có thể xử lý nhiều yêu cầu từ cùng một người dùng.enable more than one user at a time without requiring multiple copies of the program running on the computer. Multithreading can also handle multiple requests from the same user.

Multi threading với ví dụ là gì?

MultiThreading là gì?MultiThreading cho phép chúng tôi chạy nhiều luồng đồng thời.Ví dụ: trong trình duyệt web, chúng ta có thể có một luồng xử lý giao diện người dùng và song song chúng ta có thể có một luồng khác tìm hiểu dữ liệu sẽ được hiển thị.Vì vậy, đa luồng cải thiện khả năng đáp ứng của một hệ thống.enables us to run multiple threads concurrently. For example in a web browser, we can have one thread which handles the user interface, and in parallel we can have another thread which fetches the data to be displayed. So multithreading improves the responsiveness of a system.

Là đa luồng tốt trong Python?

Để tóm tắt lại, luồng trong Python cho phép nhiều luồng được tạo trong một quy trình duy nhất, nhưng do Gil, không ai trong số chúng sẽ chạy cùng một lúc.Chủ đề vẫn là một lựa chọn rất tốt khi chạy nhiều tác vụ ràng buộc I/O đồng thời.Threading is still a very good option when it comes to running multiple I/O bound tasks concurrently.