Table of Contents
Technical background of concurrent processing
Implementation mechanism of greenlet
To summarize:
Home Backend Development Python Tutorial Introduction to the use of Python greenlet and analysis of its implementation principles

Introduction to the use of Python greenlet and analysis of its implementation principles

Mar 23, 2017 pm 03:55 PM

Recently started to study Python's parallel development technology, including multi-threading, multi-process, coroutine, etc. I gradually sorted out some information on the Internet, and today I sorted out the information related to greenlet.

Technical background of concurrent processing

Parallel processing is currently receiving great attention, because in many cases, parallel computing can greatly improve system throughput, especially in the current era of multi-core and multi-processors. Therefore, ancient languages ​​like lisp have been picked up again, and functional programming has become more and more popular. Introducing a library for parallel processing in python: greenlet. Python has a very famous library called stackless, which is used for concurrent processing. It mainly uses a micro-thread called tasklet. The biggest difference between greenlet and stackless is that it is very lightweight? Not enough. The biggest difference is that greenlet requires you to handle thread switching yourself. That is to say, you need to specify which greenlet to execute now and which greenlet to execute again.

Implementation mechanism of greenlet

In the past, python was used to develop web programs, and the fastcgi mode was always used. Then multiple threads were started in each process for request processing. One problem here is that it needs Ensure that the response time of each request is very short, otherwise the server will refuse service as long as a few more slow requests are made, because no thread can respond to the request. Usually, our services will be tested for performance when they go online, so under normal circumstances, there is not much Big problem. But it is impossible to test all scenarios. Once it occurs, the user will wait for a long time without responding. Some parts are unavailable, which leads to all unavailability. Later, it was converted to coroutine, greenlet under python. So I made an implementation mechanism of it. Simple understanding.

Each greenlet is just a python object (PyGreenlet) in the heap. So it is no problem for you to create millions or even tens of millions of greenlets for a process.

typedef struct _greenlet {
	PyObject_HEAD
	char* stack_start;
	char* stack_stop;
	char* stack_copy;
	intptr_t stack_saved;
	struct _greenlet* stack_prev;
	struct _greenlet* parent;
	PyObject* run_info;
	struct _frame* top_frame;
	int recursion_depth;
	PyObject* weakreflist;
	PyObject* exc_type;
	PyObject* exc_value;
	PyObject* exc_traceback;
	PyObject* dict;
} PyGreenlet;
Copy after login

Every A greenlet is actually a function, and the context that saves the execution of this function. For a function, the context is its stack. All greenlets in the same process share a common user stack allocated by the operating system. So at the same time, only Greenlets with stack data that do not conflict use this global stack. Greenlets save the bottom and top of their stacks through stack_stop and stack_start. If the stack_stop of the greenlet to be executed overlaps with the greenlet currently in the stack, The stack data of these overlapping greenlets should be temporarily saved to the heap. The saved location is recorded through stack_copy and stack_saved, so that the stack_stop and stack_start locations in the stack can be copied from the heap back to the stack during recovery. Otherwise, the stack data will appear. will be destroyed. Therefore, these greenlets created by the application achieve concurrency by continuously copying data to the heap or from the heap to the stack. It is really comfortable to use coroutine for IO-type applications.

The following is a simple stack space model of greenlet (from greenlet.c)

A PyGreenlet is a range of C stack addresses that must be
saved and restored in such a way that the full range of the
stack contains valid data when we switch to it.

Stack layout for a greenlet:

               |     ^^^       |
               |  older data   |
               |               |
  stack_stop . |_______________|
        .      |               |
        .      | greenlet data |
        .      |   in stack    |
        .    * |_______________| . .  _____________  stack_copy + stack_saved
        .      |               |     |             |
        .      |     data      |     |greenlet data|
        .      |   unrelated   |     |    saved    |
        .      |      to       |     |   in heap   |
 stack_start . |     this      | . . |_____________| stack_copy
               |   greenlet    |
               |               |
               |  newer data   |
               |     vvv       |
Copy after login

The following is a simple greenlet code.

from greenlet import greenlet

def test1():
    print 12
    gr2.switch()
    print 34

def test2():
    print 56
    gr1.switch()
    print 78

gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch()
Copy after login

The coroutine currently discussed is generally It is supported by programming languages. At present, the languages ​​​​that I know that provide coroutine support include python, lua, go, erlang, scala and rust. The difference between coroutines and threads is that coroutines are not switched by the operating system, but by programmer coding. In other words, the switching is controlled by the programmer, so there is no so-called thread. Security Question.

All coroutines share the context of the entire process, so the exchange between coroutines is also very convenient.

Compared with the second solution (I/O multiplexing), programs written using coroutines will be more intuitive, rather than splitting a complete process into multiple managed event handlers. . The disadvantage of coroutines may be that they cannot take advantage of multi-core, but this can be solved by coroutines + processes.

Coroutines can be used to handle concurrency to improve performance, and can also be used to implement state machines to simplify programming. I use the second one more. I came into contact with python at the end of last year and learned about the coroutine concept of python. Later, I came into contact with yield processing through pycon china2011. Greenlet is also a coroutine solution, and in my opinion it is a more usable solution, especially for processing state machines.

At present, this part has been basically completed. I will take the time to summarize it later.

To summarize:

1) Multiple processes can take advantage of multi-core, but inter-process communication is troublesome. In addition, an increase in the number of processes will cause performance degradation and the cost of process switching is higher. Program flow complexity is lower than I/O multiplexing.

2) I/O multiplexing processes multiple logical processes within a process without process switching. The performance is high, and information sharing between processes is simple. However, the advantages of multi-core cannot be used. In addition, the program flow is cut into small pieces by event processing, making the program more complex and difficult to understand.

3) Threads run within a process and are scheduled by the operating system. The switching cost is low. In addition, they share the virtual address space of the process, and it is simple to share information between threads. However, thread safety issues lead to a steep learning curve for threads and are error-prone.

4) Coroutines are provided by programming languages ​​and are switched under the control of programmers, so there are no thread safety issues and can be used to handle state machines, concurrent requests, etc. But cannot take advantage of multi-core.

The above four solutions can be used together. I am more optimistic about the process + coroutine model

The above is the detailed content of Introduction to the use of Python greenlet and analysis of its implementation principles. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles