Python Threading Operations

Source: Internet
Author: User
Tags semaphore

One, Global lock

1, in Python, the execution of Python code is controlled by a Python virtual machine, while in the Python virtual machine, only one thread executes at the same time, just like running multiple processes in a single CPU system, the memory can hold multiple programs, but at any moment, Only one program runs in the CPU. Similarly, multiple threads can be "run" in the Python interpreter, but at any one time only a single thread is running in the Python interpreter.

2. Access to the Python virtual machine is controlled by the global interpreter lock "GIL", which ensures that only one thread is running at the same time.

3. In a multithreaded environment, the Python virtual machine is executed as follows:

1. Set Gil

2. Switch to a thread to run

3. Run:

A. specify the number of bytecode directives, or

b. the thread actively gives up control (can call time. Sleep(0))

4. Set the thread to sleep

5. Unlock Gil

6. Repeat all of the above steps again

Second, threading module

Python provides the "thread" and "threading" modules. In multithreaded programming, it is recommended to use the "threading" module because:

1. In the "thread" module, when the main thread exits, the other threads that are not purged will not end up being exited. However, in the "threading" module, you can ensure that all "important" sub-threads (where important sub-threads are referred to as daemons) run at the end of the process.

2, in the "threading" module is a more advanced threading module, it not only provides the thread class, but also provides a thread synchronization mechanism

Thread module built-in functions

1, thread. Start_new_thread(function, args[, kwargs=None])

This function is used to start a thread whose parameters have the following meanings:

Function: Thread task function

Args: Parameters of a thread task function "passed in as a tuple"

Kwargs: Optional Parameters

2, Thread.interrupt_main()

This function is used to interrupt the main thread

3, Thread.exit()

This function is used to exit the thread

4, Thread.get_ident()

This function is used to get the thread identification number

5, Thread.allocate_lock()

This thread is used to get the LockType object

6, Thread.stack_size([size])

This thread is used to return the creation of a new thread stack capacity with the parameters meaning:

Size: Specifies the creation of a new thread stack capacity with a value of 0 or not less than 32,768 (32KB)
LockType Object

1, Lock.acquire([Waitflag])

This function is used to request the lock object and returns True if the lock object is obtained, otherwise false

2, Lock.release()

This function is used to release the lock object "Use this function if the lock object is acquired"

3, lock.locked()

This function is used to get the state of the object lock and returns True if it is locked, otherwise false
Example:

>>> Import Thread

>>> sum = 0

/***************** Thread Task function **********************/

>>> def add(lock):

Global sum #设置为全局变量

Lock. Acquire() #加锁

I = 1

while (i < 3):

Sum = sum + 10

I = i + 1

ID = thread. Get_ident() #线程号

Print "Thread",ID,"Set sum =",sum

Lock. Release() #释放锁

/*********************** Start Thread **************************/

>>> def startTask():

Lock = thread. Allocate_lock() #申请锁对象

Task_0 = thread. Start_new_thread(add, (lock,))

Task_1 = thread. Start_new_thread(add, (lock,))

/************************ Test **************************/

>>> startTask()

>>> Thread 764 set Sum = 20

Thread 5240 Set sum=40
Threading Module

The "threading" module is based on "thread", but provides a higher thread class and synchronization mechanism.

Built-in functions

1, Threading.activecount()

This function is used to get the number of "active Thread"

2, Threading.enumerate()

This function is used to get the "active Thread" list. Note: Include broken threads and threads that have not yet started

3, Threading.currentthread()

This function is used to obtain the currently running "Thread object"

4, Threading.settrace(func)

This function is used to set trace functions for all threads that are started by the "threading" module, which is called before the "Run" Method of "thread Object" is executed, and its parameters mean:

Func: Trace Function name

5, Threading.setprofile(func)

This function is used to set the profile function of all threads initiated by the "threading" module.

6, Threading. Event()

This factory function is used to get a new "Event Object"

7, Threading. Lock()

This factory function is used to get "LockType Object"

8, Threading. Rlock()

This factory function is used to get "Rlock Object"

9, Threading. Condition ()

This factory function is used to get "Condition Object"

10, Threading. Semaphore([value])

This factory function is used to get "Semaphore Object"

11, Threading. Boundedsemaphore([value])

This factory function is used to get "bounded Semaphore Object"
Built-in class

1. Class Threading.local

Java-like threadlocal

2, class threading. Thread (Group=none, Target=none, Name=none,

Args= (), kwargs={})

The constructor parameters have the following meanings:

Functions called by the "run" function in the Target:thread class

Name: Specifies the name of the thread, with the default thread name format: "Thread-n"

Parameters of the Args:target function

1), start()

Starting the thread, it is worth noting that the method can only be called by the thread once, otherwise throwing an exception runtimeerror

2), run()

A thread task function. Often quilt class rewrite, like the Java thread Class of the Run function

3), is_alive ()

Determine if the thread is "alive"

4), Setdaemon ()

To set a thread as a daemon thread

3, Class threading. Timer (interval, function, args=[], kwargs={})

The timer class inherits the Threading.thread class, whose parameters mean:

Interval: Thread time execution interval, in seconds

The target function of the run function in the Function:thread class

Args: Parameters of the target function

1), Cancel ()

Cancel execution of a timer task
Example

/***************************timer instance ************************/

>>> def Putoutnumber():

ID = threading. CurrentThread(). GetName()

print ID,' Hello '

>>> def Starttimer():

Timer = threading. Timer(putoutnumber)

Timer. Start()

>>> starttimer()

>>> Thread-1 Hello

/**************** inherits thread and semaphore instance ********************/

>>> Import Threading

>>> class MyThread (threading. Thread):

def __init__ (Self,name,semaphore):

Threading. thread.__init__ (Self,none,none,name,none)

Self.semaphore = semaphore

def run (self): #override run function

Self.semaphore.acquire ()

i = 1

while (I < 3):

Print self.getname (), ' print ', I

i = i + 1

Self.semaphore.release ()

>>> def startTask ():

Semaphore = Threading. Semaphore ()

Thread_0 = MyThread ("Thread_0", semaphore)

Thread_1 = MyThread ("Thread_1", semaphore)

Thread_0.start ()

Thread_1.start ()

>>> StartTask ()

>>> THREAD_0 Print 1

THREAD_0 Print 2

Thread_1 Print 1

Thread_1 Print 2

Communication between/********************* processes ************************/

>>> class Managerthread (threading. Thread):

def __init__(self,name,event):

Threading. Thread. __init__(self,none,none,name,None )

Self. Event = Event

def run(self): #override Run function

print self. GetName(),' say ',' Go '

Self. Event. Set()

>>> class Peoplethread (threading. Thread):

def __init__(self,name,event):

Threading. Thread. __init__(self,none,none,name, None )

Self. Event = Event

def run(self):

Self. Event. Wait()

print self. GetName(),' Start ',' Go '

>>> def startTask():

Event = threading. Event()

M_thread = managerthread("Manager",event)

P_thread = peoplethread("People",event)

P_thread. Start()

M_thread. Start()

/************************* Test ****************************/

>>> startTask()

>>> Manager say go

People start go
Mutex built-in class

is not unlocked.

1, class Mutex.mutex

     mutex objects have two properties: Locks and queues. When the lock is not locked, the queue is empty.

   /*********************mutex Object function ********************/

    1), Mutex.test ()

          This function detects if a mutex is locked

     2), Mutex.testandset ()

            This function is used to detect if a mutex is locked and if it is not locked, it is locked and returns true, otherwise false is returned. It is important to note that this function is atomic operation

     3), Mutex.lock ( function, argument

            This function is used to perform function functions (argument) "If the mutex is not locked." If the mutex lock is locked, the function (argument) is placed in the queue

     4), Mutex.unlock ()

          This function is used to unlock the mutex "if the queue is empty". If the queue is not empty, the first function (argument) is taken out of the queue and the
Example

>>> Import Mutex

>>> def putouttask(text):

Print text

>>> def startTask():

M_metux = Mutex. Mutex()

M_metux. Lock(putouttask,' I am task_0 ')

M_metux. Lock(putouttask,' T am task_1 ')

M_metux. Lock(putouttask,' I am task_2 ')

M_metux. Lock(putouttask,' T am task_3 ')

M_metux. Lock(putouttask,' I am task_4 ')

M_metux. Lock(putouttask,' T am task_5 ')

while (M_metux. Test()):

M_metux. Unlock()

M_metux. Unlock()

/************************** Test ***************************/

>>> startTask()

I am TASK_0

T am Task_1

I am Task_2

T am Task_3

I am Task_4

T am Task_5

Python Threading Operations

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.