Python module learning-thread multi-thread processing

Source: Internet
Author: User

This period of time has been in use
Python
Write a game server program. In the process of writing, it is inevitable to use multiple threads to process interaction with the client.
Python
The standard library provides
Thread
And
Threading
Two modules are used to support multithreading. Where,
Thread
The module processes and controls threads in a low-level and original way, while
Threading
Module
Thread
Further encapsulation provides more convenient
API
To process threads.
Although
Thread
No
Threading
But it is more flexible. Introduction Today
Thread
Basic use of modules, next
Introduction
Threading
Module.

In Introduction
Thread
Before that, let's take a look at a piece of code and guess what the output result is on the console after the program is completed?

# Coding = GBK <br/> Import thread, time, random <br/> COUNT = 0 <br/> def threadtest (): <br/> global count <br/> for I in xrange (10000): <br/> count + = 1 <br/> for I in range (10 ): <br/> thread. start_new_thread (threadtest, () # If you are not familiar with the start_new_thread function, don't worry, I will explain it now <br/> time. sleep (3) <br/> Print count # What is count? Is it 10000*10? <Br/>

Thread. start_new_thread

(
Function

, ARGs
[
, Kwargs
]

)

The function creates a new thread and returns the identifier of the thread (the identifier is an integer ). Parameters
Function
Indicates the function to be executed immediately after the thread is created. The Parameter
ARGs
Is the parameter of the function, which is a tuples; the second parameter
Kwargs
It is optional and provides the name parameter dictionary for the function. After the function is executed, the thread automatically exits. If the function encounters an unhandled exception during execution, the thread will exit, but it will not affect the execution of other threads.
The following is a simple example:

# Coding = GBK <br/> Import thread, time <br/> def threadfunc (A = none, B = none, c = none, D = none ): <br/> Print time. strftime ('% H: % m: % s', time. localtime (), a <br/> time. sleep (1) <br/> Print time. strftime ('% H: % m: % s', time. localtime (), B <br/> time. sleep (1) <br/> Print time. strftime ('% H: % m: % s', time. localtime (), C <br/> time. sleep (1) <br/> Print time. strftime ('% H: % m: % s', time. localtime (), d <br/> T Ime. sleep (1) <br/> Print time. strftime ('% H: % m: % s', time. localtime (), 'over' </P> <p> thread. start_new_thread (threadfunc, (3, 4, 5, 6) # create a thread and execute the threadfunc function. <Br/> time. Sleep (5) <br/>

Thread. Exit
()

End the current thread. This function is triggered.
Systemexit
Exception. If the exception is not handled, the thread ends.

Thread. get_ident
()

Returns the identifier of the current thread. The identifier is a non-zero integer.

Thread. interrupt_main
()

Triggered in the main thread
Keyboardinterrupt


Exception. Subthreads can use this method to interrupt the main thread. The following example shows how to call a sub-thread.
Interrupt_main
, Capture exceptions in the main thread
:

Import thread, time <br/> thread. start_new_thread (lambda: (thread. interrupt_main (),), () <br/> try: <br/> time. sleep (2) <br/> comment t keyboardinterrupt, E: <br/> Print 'error: ', e <br/> Print 'over' <br/>

 

The following describes
Thread
The module is cumbersome and can ensure that only one thread can access Shared resources at any time.

Thread. locktype


Yes
Thread
Type defined in the module. It has the following methods:

Lock. Acquire
(
[

Waitflag
]

)

Obtain the required information. The function returns a Boolean value. If the value is obtained successfully, the return value is
True
Otherwise, return
False
. Parameters
Waitflag

The default value is a non-zero integer, indicating that if the zombie has been occupied by other threads, the current thread will wait until the other threads are released, and then obtain the access bot. If you set the parameters
Waitflag
Set
0
The current thread will try to obtain the required information. No matter whether the required information is occupied by other threads or not, the current thread will not wait.

Lock. Release
()

Release the occupied items.

Lock. Locked
()

Determine whether or not the object is occupied.

Now let's look back at the Code provided at the beginning: the Code defines a function.
Threadtest
It increases global variables one by one
10000
And then enabled in the main thread
10
Subthread to call
Threadtest
Function. But the results are not unexpected.
10000*10
The main reason is
Count
. Global Variables
Count
Is a shared resource, and its operations should be serialized. The following code is modified:
Count
During the operation, perform the operation. Check whether the running result is as expected. Modified code:

# Coding = GBK <br/> Import thread, time, random <br/> COUNT = 0 <br/> lock = thread. allocate_lock () # create a wretched object <br/> def threadtest (): <br/> global count, lock <br/> lock. acquire () # obtain </P> <p> for I in xrange (10000): <br/> count + = 1 </P> <p> lock. release () # Release <br/> for I in xrange (10): <br/> thread. start_new_thread (threadtest, () <br/> time. sleep (3) <br/> Print count <br/>

Isn't the thread module as hard as you think! Simple is beautiful, and this is Python. For more information about the thread module, refer to the python manual thread

Module

 

 


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.