Home Backend Development Python Tutorial python thread practices

python thread practices

Dec 09, 2016 am 10:42 AM
python

"""" There are two ways to use threads in Python: functions or classes to wrap thread objects.

1. Functional: Call the start_new_thread() function in the thread module to generate a new thread. The thread can end by waiting for the thread to end naturally, or by calling the thread.exit() or thread.exit_thread() method in the thread function.
import time
import thread

def timer(no,interval):
cnt=0

while cnt<10:
print 'thread(%d)'%(cnt)
time.sleep(interval)
cnt= cnt+1


def test():
thread.start_new_thread(timer,(1,1))
thread.start_new_thread(timer,(2,2))

if __name__=='__main__':
print ' thread starting'
test()
time.sleep(20)
thread.exit_thread()
print 'exit...'
2. Create a subclass of threading.Thread to wrap a thread object,
threading.Thread class Usage:

1, call threading.Thread.__init__(self, name = threadname) in the __init__ of your own thread class

Threadname is the name of the thread

2, run(), usually needs to be rewritten and written The code implements the required functionality.

3, getName(), get the thread object name

4, setName(), set the thread object name

5, start(), start the thread

6, jion([timeout]), wait for another thread to end and then run again.

7, setDaemon(bool), sets whether the sub-thread ends with the main thread, and must be called before start(). Default is False.

8, isDaemon(), determines whether the thread ends with the main thread.

9, isAlive(), check whether the thread is running.
import threading
import time

class timer(threading.Thread):
def __init__(self,num,interval):
threading.Thread.__init__(self)
self.thread_num=num
self.interval=interval
self .thread_stop=False

def run(self):
while not self.thread_stop:
print 'thread object (%d), time %sn' %(self.thread_num,time.ctime())
time.sleep( self.interval)

def stop(self):
self.thread_stop=True

def test():
thread1=timer(1,1)
thread2=timer(2,2)
thread1.start()
thread2.start()
time.sleep(10)
thread1.stop()
thread2.stop()
return

if __name__=='__main__':
test()
"""
"""
Question The reason is that the access of multiple threads to the same resource is not controlled, causing data damage and making the results of thread operation unpredictable. This phenomenon is called "thread unsafe".
import threading
import time

class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg='I am '+ self.getName ()+'@'+str(i)
          print msg  

def test():
  for i in range(5):
  t=MyThread()
  t.start()

if __name__=='__main__ ':
test()

The above example leads to the most common problem of multi-threaded programming: data sharing. When multiple threads modify a certain shared data, synchronization control is required.

Thread synchronization can ensure that multiple threads safely access competing resources. The simplest synchronization mechanism is to introduce a mutex lock. A mutex introduces a state to a resource: locked/unlocked. When a thread wants to change shared data, it must first lock it. At this time, the status of the resource is "locked" and other threads cannot change it; until the thread releases the resource and changes the status of the resource to "unlocked", other threads can Lock the resource again. The mutex lock ensures that only one thread performs writing operations at a time, thereby ensuring the correctness of data in multi-threaded situations. Among them, the lock method acquire can have an optional parameter timeout for the timeout period. If timeout is set, the return value can be used to determine whether the lock has been obtained after the timeout, so that some other processing can be performed

The Lock class is defined in the threading module
import threading
import time

class MyThread(threading.Thread ):
def run(self):
global num
time.sleep(1)

if mutex.acquire(): num=num+1
print self.name+' set num to '+str(num)+'n'
mutex.release()
num=0
mutex=threading.Lock()

def test():
for i in range(5):
t=MyThread()
t.start()

if __name__=='__main__':
test()
"""
"""A simpler deadlock situation is when a thread "iteratively" requests the same resource, which will directly cause a deadlock:
import threading
import time

class MyThread(threading.Thread) :
  def run(self):
                                                                          using using ’ using ’s ’ s ’ using ’s ’ using ’ s ‐ ‐ ‐ ‐                                                          name+' set num to '+str(num) G Print MSG in Mutex.acquire ()
mutex.release ()
mutex.release ()
num = 0
mutex = Threading.lock ()
for I in Range (5):
T = MyThread()
t.start()
if __name__ == '__main__':
test()
In order to support multiple requests for the same resource in the same thread, python provides a "reentrant lock": threading.RLock. RLock maintains a Lock and a counter variable internally. The counter records the number of acquires, so that the resource can be required multiple times. Until all acquires of a thread are released, other threads can obtain resources. In the above example, if RLock is used instead of Lock, no deadlock will occur:
import threading
import time

class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1)

                                                                       if mutex. re()
                                                        use using use using use using using using                 through through ‐ ‐ off ‐ ‐ ‐ ‐ ‐ ‐              ()
num = 0
mutex = threading.RLock()
def test():
for i in range(5):
t = MyThread()
t.start()
if __name__ == '__main__':
Test()
"""

"""
Python multi-threaded programming (5): Condition variable synchronization

Mutex lock is the simplest thread synchronization mechanism. The Condition object provided by Python provides a solution to complex thread synchronization issues support. Condition is called a condition variable. In addition to providing acquire and release methods similar to Lock, it also provides wait and notify methods. The thread first acquires a condition variable and then determines some conditions. If the condition is not met, wait; if the condition is met, perform some processing to change the condition, and notify other threads through the notify method. Other threads in the wait state will re-judge the condition after receiving the notification. This process is repeated continuously to solve complex synchronization problems.

It can be thought that the Condition object maintains a lock (Lock/RLock) and a waiting pool. The thread obtains the Condition object through acquire. When the wait method is called, the thread releases the lock inside the Condition and enters the blocked state. At the same time, the thread is recorded in the waiting pool. When the notify method is called, the Condition object will select a thread from the waiting pool and notify it to call the acquire method to try to acquire the lock.

The constructor of the Condition object can accept a Lock/RLock object as a parameter. If not specified, the Condition object will create an RLock internally.

In addition to the notify method, the Condition object also provides the notifyAll method, which can notify all threads in the waiting pool to try to acquire the internal lock. Due to the above mechanism, threads in the waiting state can only be awakened through the notify method, so the function of notifyAll is to prevent threads from being in a silent state forever.

The classic problem that demonstrates condition variable synchronization is the producer and consumer problem: Suppose there is a group of producers (Producer) and a group of consumers (Consumer) interacting with products through a market. The producer's "strategy" is to produce 100 products and put them on the market if the remaining products on the market are less than 1,000; while the consumer's "strategy" is to produce more than 100 products on the market. Consume 3 products. The code to use Condition to solve the problem of producers and consumers is as follows:
import threading
import time

class Producer(threading.Thread):
def run(self):
global count
while True:
if con.acquire() :
if count & gt; 1000:
con.wait ()
else:
Count = Count+100
Print Self.name+'Produce 100, Count ='+Str (Count)

TIME. Sleep (1)

class Customer(threading.Thread):
def run(self):
global count
while True:
if con.acquire():
if count>100:
count=count-100
            print self .name+ 'consume 100, count='+str(count)
else:
con.wait()
con.release() time.sleep(1)

count=500
con=threading.Condition()

def test():
for i in range(5):
p=Producer()
p.start()
c=Customer()
c.start()
print i


if __name__==' __main__':
test()
The default global variables in python can be read in the function, but cannot be written. However,
are only readable for con, so there is no need to introduce global """

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)

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.

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.

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.

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.

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.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

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.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles