Višenitnost u Python s primjerom: Naučite GIL u Python
⚡ Pametni sažetak
Višenitnost u Python runs several threads inside one process so they share memory and work concurrently. The threading module creates and manages these threads, while the Global Interpreter Lock limits true parallelism, making the technique best for input/output-bound tasks.

The Python programming language allows you to use multiprocessing or multithreading. In this tutorial, you will learn how to write multithreaded applications in Python.
Što je nit?
A thread is a unit of execution in concurrent programming. Multithreading is a technique that allows a CPU to execute many tasks of one process at the same time. These threads can execute individually while sharing their process resources.
Što je proces?
A process is basically the program in execution. When you start an application on your computer (like a browser or text editor), the operating system creates a proces.
U čemu je Multithreading Python?
Višenitnost u Python programming is a well-known technique in which multiple threads in a process share their data space with the main thread, which makes information sharing and communication within threads easy and efficient. Threads are lighter than processes. Multiple threads may execute individually while sharing their process resources. The purpose of multithreading is to run multiple tasks and functions at the same time.
Što je višeprocesiranje?
višeobradbeni omogućuje vam pokretanje više nepovezanih procesa istovremeno. Ovi procesi ne dijele svoje resurse i komuniciraju putem IPC-a.
Python Multithreading vs Multiprocessing
To understand processes and threads, consider this scenario: An .exe file on your computer is a program. When you open it, the OS loads it into memory, and the CPU executes it. The instance of the program that is now running is called the process.
Every process has two fundamental components:
- The Code
- Podatak
Sada, proces može sadržavati jedan ili više poddijelova tzv teme. This depends on the OS architecture. You can think of a thread as a section of the process that can be executed separately by the operating system.
In other words, it is a stream of instructions that can be run independently by the OS. Threads within a single process share the data of that process and are designed to work together to facilitate parallelism.
Zašto koristiti Multithreading?
Multithreading vam omogućuje rastavljanje aplikacije na više podzadataka i pokretanje tih zadataka istovremeno. Ako pravilno koristite multithreading, brzina vaše aplikacije, performanse i renderiranje mogu se poboljšati.
Python Višenitnost
Python supports constructs for both multiprocessing and multithreading. In this tutorial, you will primarily focus on implementing višenitni aplikacije sa Python. There are two main modules that can be used to handle threads in Python:
- The nit modul, i
- The threading modul
Međutim, u Python, there is also something called a global interpreter lock (GIL). It does not allow for much performance gain and may even smanjiti performanse nekih višenitnih aplikacija. Naučit ćete sve o tome u sljedećim odjeljcima ovog vodiča.
Moduli Thread i Threading
Dva modula o kojima ćete naučiti u ovom vodiču su modul niti i modul navoja.
Međutim, modul niti je odavno zastario. Počevši od Python 3, označen je kao zastario i dostupan je samo kao _thread za kompatibilnost unazad.
Trebali biste koristiti višu razinu threading module for applications that you intend to deploy. The thread module has only been covered here for educational purposes.
Modul niti
Sintaksa za stvaranje nove niti pomoću ovog modula je sljedeća:
thread.start_new_thread(function_name, arguments)
U redu, sada ste pokrili osnovnu teoriju za početak kodiranja. Dakle, otvorite svoje IDLE ili bilježnicu i upišite sljedeće:
import time import _thread def thread_test(name, wait): i = 0 while i <= 3: time.sleep(wait) print("Running %s\n" %name) i = i + 1 print("%s has finished execution" %name) if __name__ == "__main__": _thread.start_new_thread(thread_test, ("First Thread", 1)) _thread.start_new_thread(thread_test, ("Second Thread", 2)) _thread.start_new_thread(thread_test, ("Third Thread", 3))
Spremite datoteku i pritisnite F5 za pokretanje programa. Ako je sve učinjeno ispravno, ovo je rezultat koji biste trebali vidjeti:
You will learn more about race conditions and how to handle them in the upcoming sections.
OBJAŠNJENJE ŠIFRE
- These statements import the time and thread module, which are used to handle the execution and delaying of the Python teme.
- Ovdje ste definirali funkciju tzv test_niti, koji će biti pozvan od strane započeti_novu_nit method. The function runs a while loop for four iterations and prints the name of the thread that called it. Once the iteration is complete, it prints a message saying that the thread has finished execution.
- Ovo je glavni dio vašeg programa. Ovdje jednostavno nazovete započeti_novu_nit metoda s test_niti function as an argument. This will create a new thread for the function you pass as an argument and start executing it. Note that you can replace this (thread_test) with any other function that you want to run as a thread.
Modul Threading
This module is the high-level implementation of threading in Python and the de facto standard for managing multithreaded applications. It provides a wide range of features when compared to the thread module.
Struktura Threading modula
Ovdje je popis nekih korisnih funkcija definiranih u ovom modulu:
| Naziv funkcije | Description |
|---|---|
| activeCount() | Vraća broj od Nit objects that are still alive. |
| trenutna nit() | Vraća trenutni objekt klase Thread. |
| nabrojati() | Ispisuje sve aktivne Thread objekte. |
| isDaemon() | Vraća true ako je nit demon. |
| živ je() | Vraća true ako je nit još živa. |
| Thread Metode klase | |
| početak() | Pokreće aktivnost niti. Mora se pozvati samo jednom za svaku nit jer će izbaciti pogrešku vremena izvođenja ako se pozove više puta. |
| trčanje() | Ova metoda označava aktivnost niti i može je nadjačati klasa koja proširuje klasu Thread. |
| pridružiti() | Blokira izvođenje drugog koda sve dok se nit na kojoj je pozvana metoda join() ne prekine. |
Backstory: The Thread Class
Before you start coding multithreaded programs using the threading module, it is crucial to understand the Thread class. The thread class is the primary class that defines the template and the operations of a thread in Python.
The most common way to create a multithreaded Python application is to declare a class that extends the Thread class and overrides its run() method.
Klasa Thread, ukratko, označava sekvencu koda koja se izvodi zasebno nit kontrole.
Dakle, kada pišete višenitnu aplikaciju, učinit ćete sljedeće:
- define a class that extends the Thread class
- Nadjačaj __init__ konstruktor
- Nadjačaj trčanje() način
Nakon što je objekt niti napravljen, početak() method can be used to begin the execution of this activity, and the pridružiti() metoda se može koristiti za blokiranje svih ostalih kodova dok se trenutna aktivnost ne završi.
Now, let us try using the threading module to implement your previous example. Again, fire up your IDLE i upišite sljedeće:
import time import threading class threadtester (threading.Thread): def __init__(self, id, name, i): threading.Thread.__init__(self) self.id = id self.name = name self.i = i def run(self): thread_test(self.name, self.i, 5) print ("%s has finished execution " %self.name) def thread_test(name, wait, i): while i: time.sleep(wait) print ("Running %s \n" %name) i = i - 1 if __name__=="__main__": thread1 = threadtester(1, "First Thread", 1) thread2 = threadtester(2, "Second Thread", 2) thread3 = threadtester(3, "Third Thread", 3) thread1.start() thread2.start() thread3.start() thread1.join() thread2.join() thread3.join()
Ovo će biti rezultat kada izvršite gornji kod:
OBJAŠNJENJE ŠIFRE
- This part is the same as our previous example. Here, you import the time and thread module, which are used to handle the execution and delays of the Python teme.
- U ovom dijelu stvarate klasu koja se zove threadtester, koja nasljeđuje ili proširuje Nit class of the threading module. This is one of the most common ways of creating threads in Python. However, you should only override the constructor and the trčanje() način u vašoj aplikaciji. Kao što možete vidjeti u gornjem uzorku koda, __init__ metoda (konstruktor) je nadjačana. Slično tome, također ste nadjačali trčanje() metoda. Sadrži kod koji želite izvršiti unutar niti. U ovom primjeru pozvali ste funkciju thread_test().
- This is the thread_test() method, which takes the value of i as an argument, decreases it by 1 at each iteration, and loops through the rest of the code until i becomes 0. In each iteration, it prints the name of the currently executing thread and sleeps for wait seconds (which is also taken as an argument).
- thread1 = threadtester(1, “First Thread”, 1) Ovdje stvaramo nit i prosljeđujemo tri parametra koja smo deklarirali u __init__. Prvi parametar je ID niti, drugi parametar je naziv niti, a treći parametar je brojač, koji određuje koliko puta bi se trebala pokrenuti while petlja.
- thread2.start() The start method is used to start the execution of a thread. Internally, the start() function calls the run() method of your class.
- thread3.join() Metoda join() blokira izvođenje drugog koda i čeka dok nit na kojoj je pozvana završi.
As you already know, the threads that are in the same process have access to the memory and data of that process. As a result, if more than one thread tries to change or access the data simultaneously, errors may creep in.
In the next section, you will see the different kinds of complications that can show up when threads access data and the critical section without checking for existing access transactions.
Uvjeti zastoja i utrke
Before learning about deadlocks and race conditions, it will be helpful to understand a few basic definitions related to concurrent programming:
- Kritični odjeljak: It is a fragment of code that accesses or modifies shared variables and must be performed as an atomic transaction.
- Prekidač konteksta: It is the process that a CPU follows to store the state of a thread before changing from one task to another so that it can be resumed from the same point later.
Zastoji
Zastoji are the most feared issue that developers face when writing concurrent/multithreaded applications in Python. The best way to understand deadlocks is by using the classic computer science example problem known as the Objed Philosophers Problem.
Izjava o problemu za filozofe objedovanja je sljedeća:
Five philosophers are seated at a round table with five plates of spaghetti (a type of pasta) and five forks, as shown in the diagram.
Objed Philosophers Problem
U bilo kojem trenutku, filozof mora ili jesti ili razmišljati.
Štoviše, filozof mora uzeti dvije vilice koje su mu susjedne (tj. lijevu i desnu vilicu) prije nego što može jesti špagete. Problem zastoja javlja se kada svih pet filozofa istovremeno podignu svoje desne vilice.
Budući da svaki od filozofa ima jednu vilicu, svi će čekati da ostali odlože vilicu. Kao rezultat toga, nitko od njih neće moći jesti špagete.
Slično, u konkurentnom sustavu, zastoj se događa kada različite niti ili procesi (filozofi) pokušavaju steći dijeljene resurse sustava (forkovi) u isto vrijeme. Kao rezultat toga, niti jedan od procesa nema priliku za izvršenje jer čekaju drugi resurs koji drži neki drugi proces.
Uvjeti utrke
A race condition is an unwanted state of a program that occurs when a system performs two or more operations simultaneously. For example, consider this simple for loop:
i=0; # a global variable for x in range(100): print(i) i+=1;
Ako stvarate n number of threads that run this code at once, you cannot determine the value of i (which is shared by the threads) when the program finishes execution. This is because in a real multithreading environment, the threads can overlap, and the value of i that was retrieved and modified by a thread can change in between when some other thread accesses it.
These are the two main classes of problems that can occur in a multithreaded or distributed Python application. In the next section, you will learn how to overcome this problem by synchronizing threads.
Synchronizirajući niti
Za rješavanje uvjeta utrke, zastoja i drugih problema temeljenih na nitima, modul za niti pruža Zaključati objekt. Ideja je da kada nit želi pristup određenom resursu, dobiva zaključavanje za taj resurs. Jednom kada nit zaključa određeni resurs, nijedna druga nit mu ne može pristupiti dok se zaključavanje ne oslobodi. Kao rezultat toga, promjene resursa bit će atomske, a uvjeti utrke bit će izbjegnuti.
Zaključavanje je primitiv sinkronizacije niske razine implementiran od strane _thread module. At any given time, a lock can be in one of two states: zaključan or otključan. Podržava dvije metode:
- acquire(): When the lock state is unlocked, calling the acquire() method will change the state to locked and return. However, if the state is locked, the call to acquire() is blocked until the release() method is called by some other thread.
- release(): Metoda release() koristi se za postavljanje stanja na otključano, tj. za otključavanje. Može se pozvati bilo kojom niti, ne nužno onom koja je stekla zaključavanje.
Here is an example of using locks in your apps. Fire up your IDLE i upišite sljedeće:
import threading lock = threading.Lock() def first_function(): for i in range(5): lock.acquire() print ('lock acquired') print ('Executing the first funcion') lock.release() def second_function(): for i in range(5): lock.acquire() print ('lock acquired') print ('Executing the second funcion') lock.release() if __name__=="__main__": thread_one = threading.Thread(target=first_function) thread_two = threading.Thread(target=second_function) thread_one.start() thread_two.start() thread_one.join() thread_two.join()
Sada pritisnite F5. Trebali biste vidjeti ovakav izlaz:
OBJAŠNJENJE ŠIFRE
- Ovdje jednostavno stvarate novu bravu pozivom threading.Lock() tvornička funkcija. Interno, Lock() vraća instancu najučinkovitije konkretne klase Lock koju održava platforma.
- U prvoj izjavi zaključavanje dobivate pozivanjem metode Acquisi(). Kada je zaključavanje odobreno, ispisujete "zaključavanje stečeno" na konzolu. Nakon što sav kod za koji želite da se nit pokrene završi s izvršenjem, otključavate zaključavanje pozivanjem metode release().
The theory is fine, but how do you know that the lock really worked? If you look at the output, you will see that each of the print statements is printing exactly one line at a time. Recall that, in an earlier example, the outputs from print were haphazard because multiple threads were accessing the print() method at the same time. Here, the print function is called only after the lock is acquired. So, the outputs are displayed one at a time and line by line.
Apart from locks, Python also supports some other mechanisms to handle thread synchronization, as listed below:
- RLocks
- Semaphores
- Uvjeti
- Događaji, i
- Prepreke
Globalno zaključavanje tumača (i kako to riješiti)
Prije nego što uđemo u detalje Python’s GIL, let us define a few terms that will be useful in understanding the upcoming section:
- CPU-bound code: this refers to any piece of code that will be directly executed by the CPU.
- I/O-bound code: this can be any code that accesses the file system through the OS.
- CPython: to je referenca izvršenje of Python i može se opisati kao tumač napisan u C i Python (programski jezik).
U čemu je GIL Python?
Globalna brava tumača (GIL) in Python is a process lock or a mutex used while dealing with the processes. It makes sure that one thread can access a particular resource at a time, and it also prevents the use of objects and bytecodes at once. This benefits the single-threaded programs with a performance increase. GIL in Python is very simple and easy to implement.
Zaključavanje se može koristiti kako bi se osiguralo da samo jedna nit ima pristup određenom resursu u određenom trenutku.
Jedna od značajki Python is that it uses a global lock on each interpreter process, which means that every process treats the Python interpreter itself as a resource.
For example, suppose you have written a Python program that uses two threads to perform both CPU and ‘I/O’ operations. When you execute this program, this is what happens:
- The Python interpreter creates a new process and spawns the threads.
- Kada se nit-1 pokrene, prvo će nabaviti GIL i zaključati ga.
- Ako se nit-2 sada želi izvršiti, morat će pričekati da se GIL oslobodi čak i ako je drugi procesor slobodan.
- Sada, pretpostavimo da thread-1 čeka I/O operaciju. U to će vrijeme osloboditi GIL, a thread-2 će ga preuzeti.
- Nakon dovršetka I/O operacija, ako se nit-1 sada želi izvršiti, ponovno će morati pričekati da nit-2 oslobodi GIL.
Due to this, only one thread can access the interpreter at any time, meaning that there will be only one thread executing Python code at a given point in time.
This is alright in a single-core processor because it would be using time slicing (see the first section of this tutorial) to handle the threads. However, in the case of multi-core processors, a CPU-bound function executing on multiple threads will have a considerable impact on the program’s efficiency since it will not actually be using all the available cores at the same time.
Zašto je GIL bio potreban?
CPython garbage collector uses an efficient memory management technique known as reference counting. Here is how it works: Every object in Python has a reference count, which is increased when it is assigned to a new variable name or added to a container (like tuples, lists, etc.). Likewise, the reference count is decreased when the reference goes out of scope or when the del statement is called. When the reference count of an object reaches 0, it is garbage collected, and the allotted memory is freed.
But the problem is that the reference count variable is prone to race conditions like any other global variable. To solve this problem, the developers of Python decided to use the global interpreter lock. The other option was to add a lock to each object, which would have resulted in deadlocks and increased overhead from acquire() and release() calls.
Therefore, GIL is a significant restriction for multithreaded Python programs running heavy CPU-bound operations (effectively making them single-threaded). If you want to make use of multiple CPU cores in your application, use the višeobradbeni modul umjesto toga.








