Table of Contents
1. Threading
2. Lock
Home Backend Development Python Tutorial Multi-process and multi-thread examples in Python (2) Programming methods

Multi-process and multi-thread examples in Python (2) Programming methods

Jun 01, 2017 am 10:01 AM

In the previous chapter, we learned some basic methods of Python multi-process programming: using the Process, Pool, Queue, Lock, Pipe and other classes provided by the cross-platform multi-process module multiprocessing to implement sub-process creation, process pool (batch) Create child processes and manage the maximum number of child processes) and inter-process communication. In this chapter, you will learn about multi-threaded programming methods in Python.

1. Threading

Thread is the smallest unit for the operating system to perform tasks. The threading module is provided in the Python standard library, which provides very convenient support for multi-threaded programming.

The following is the code for using threading to implement multi-threading:

 1 #!/usr/bin/python 2 # -*- coding: utf-8 -* 3 author = 'zni.feng' 4 import  sys 5 reload (sys) 6 sys.setdefaultencoding('utf-8') 7  8 import threading, time 9 10 def test(index):11     print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))12     print 'thread %s starts.' % threading.current_thread().name13     print 'the index is %d' % index14     time.sleep(3)15     print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))16     print 'thread %s ends.' % threading.current_thread().name17 18 if name == "main":19     print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))20     print 'thread %s starts.' % threading.current_thread().name21     #创建线程22     my_thread = threading.Thread(target = test, args=(1,) , name= 'zni_feng_thread')23     #等待2s24     time.sleep(2)25     #启动线程26     my_thread.start()27     #等待线程结束28     my_thread.join()29     print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))30     print 'thread %s ends.' % threading.current_thread().name
Copy after login

The output result is:

2017-01-12 22:06:32
thread MainThread starts.
2017-01-12 22:06:34
thread zni_feng_thread starts.
the index is 1
2017-01-12 22:06:37
thread zni_feng_thread ends.
2017-01-12 22:06:37
thread MainThread ends.
[Finished in 5.1s]
Copy after login

Among them, the current_thread() function of the threading module will Returns the instance of the current thread.

2. Lock

The biggest difference between multi-process and multi-thread is that in multi-process, the same variable has a copy in each process. Do not affect each other. In multi-threading, all variables are shared by all threads, so any shared variable can be modified by any thread. Therefore, the biggest danger in sharing data between threads is that multiple threads change a variable at the same time. In order to solve this problem, we can use the Lock class of the threading module to lock the shared variables.

Let’s first look at an example of using multiple threads to write the same shared variable without locking:

 1 #!/usr/bin/python 2 # -*- coding: utf-8 -* 3 author = 'zni.feng' 4 import  sys 5 reload (sys) 6 sys.setdefaultencoding('utf-8') 7 import threading 8  9 class Account:10     def init(self):11         self.balance = 012 13     def add(self):14         for i in range(0,100000):15             self.balance += 116 17     def delete(self):18         for i in range(0,100000):19             self.balance -=1 
20 21 if name == "main":22     account  = Account()23     #创建线程24     thread_add = threading.Thread(target=account.add, name= 'Add')25     thread_delete = threading.Thread(target=account.delete, name= 'Delete')26 27     #启动线程28     thread_add.start()29     thread_delete.start()30     31     #等待线程结束32     thread_add.join()33     thread_delete.join()34 35     print 'The final balance is: ' + str(account.balance)
Copy after login

The running result is:

The final balance is: -51713
[Finished in 0.1s]
Copy after login

It can be found that every time it is run, it The final results will be different, and none of them will be 0. This is because conflicts occur when different threads modify the same variable at the same time, and some intermediate variables are not used in order.

Now we use Lock to lock the program:

 1 #!/usr/bin/python 2 # -*- coding: utf-8 -* 3 author = 'zni.feng' 4 import  sys 5 reload (sys) 6 sys.setdefaultencoding('utf-8') 7 import threading 8  9 class Account:10     def init(self):11         self.balance = 012 13     def add(self, lock):14         #获得锁15         lock.acquire()16         for i in range(0,100000):17             self.balance += 118         #释放锁19         lock.release()20 21     def delete(self, lock):22         #获得锁23         lock.acquire()24         for i in range(0,100000):25             self.balance -=1 
26         #释放锁27         lock.release()28 29 30 if name == "main":31     account  = Account()32     lock = threading.Lock()33     #创建线程34     thread_add = threading.Thread(target=account.add, args=(lock, ), name= 'Add')35     thread_delete = threading.Thread(target=account.delete, args=(lock, ), name= 'Delete')36 37     #启动线程38     thread_add.start()39     thread_delete.start()40     41     #等待线程结束42     thread_add.join()43     thread_delete.join()44 45     print 'The final balance is: ' + str(account.balance)
Copy after login

It can be found that no matter how many times it is executed, the balance result is 0. If you print out the results of each balance calculation, you will also find that when one thread starts executing, the other thread will wait until the previous thread has finished executing (to be precise, lock.release() has finished executing) before starting. implement.

The final balance is: 0
[Finished in 0.1s]
Copy after login

【Related recommendations】

1. Examples of multi-process and multi-threading in Python (1)

2. Recommended in Python Use multiprocessing instead of multithreading? Share the reasons why it is recommended to use multi-process

3. Is multi-process or multi-thread faster in python?

4. Detailed introduction to Python processes, threads, and coroutines

5. Python concurrent programming thread pool/process pool

The above is the detailed content of Multi-process and multi-thread examples in Python (2) Programming methods. 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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles