Multi-tasking-Threading Basics and summary

Source: Internet
Author: User

First, the understanding of the thread

1. A program runs at least one process, and a process has at least one thread
2. Processor CPU is assigned to threads, that is, the CPU is actually running code in the thread
3. When assigning the CPU to the thread, it is done by the time slice rotation method
4. A process is the unit in which the operating system allocates programs to execute resources, and the thread is an entity of the process and is the unit of CPU dispatch and allocation.

Two ways of realizing multithreading in Python

1. Create a function and pass in the thread object

Examples are as follows:

#Introducing the Threading threading module    ImportThreadingImport Timedefdownload_music ():"""Download 5 Seconds to download the song"""             forIinchRange (5): Time.sleep (1)#Sleep 1 seconds            Print("---is downloading song%d---"%i)defplay_music ():"""simulate playing songs, it takes 5 seconds to complete the download"""            forIinchRange (5): Time.sleep (1)#Sleep 1 seconds            Print("---is playing song%d---"%i)defMain ():#Create a Thread object T1        #Target: The code to execute for the newly opened threadT1 = Threading. Thread (target=download_music) T2= Threading. Thread (target=play_music) T1.start ()#start the thread, since the thread starts executingT2.start ()if __name__=='__main__': Main ()

2. Inherit the thread class, create a new class, write the code you want to execute into the run function

#custom classes, inheriting threading. Thread    classMyThread (Threading. Thread):defRun (self): forIinchRange (5): Time.sleep (1)                    #The Name property holds the names of the current thread.msg ="I ' m"+ Self.name +' @ '+Str (i)Print(msg)if __name__=='__main__':        #creating thread objects from MythreadT1 =MyThread ()#Start thread ExecutionT1.start ()

Third, when the thread is opened and when it ends

1. When the child thread is turned on and when it runs
When you call Thread.Start (), open the thread, and then run the thread's code

2. When the child thread ends
When a child thread finishes executing a statement in a function pointed to by target, or when the run function code in the thread finishes executing, the current child thread ends immediately

3. View the current number of threads
All currently running threads can be enumerated through threading.enumerate ()

4. When the main thread ends
The main thread ends after all child threads have finished executing

Iv. multithreading (problems with shared global variables)

1. Sharing global variables across all threads within a process makes it easy to share data among multiple threads
2. The disadvantage is that multithreading can arbitrarily modify global variables to cause confusion of global variables (that is, thread non-security)
3. If multiple threads operate on the same global variable at the same time, there is a resource contention problem, which results in incorrect data, which can lead to thread safety issues

Five, mutual exclusion lock

1. Synchronization control is required when multiple threads modify a shared data at almost the same time

2. Thread synchronization ensures that multiple threads secure access to competing resources, and the simplest synchronization mechanism is to introduce mutexes.

3. Mutex introduces a state to a resource: locked/non-locked

4. When a thread changes the shared data, it locks it, the state of the resource is locked, the other thread cannot change, until the thread frees the resource, the state of the resource becomes "non-locked", and the other thread can lock the resource again. The mutex ensures that only one thread is written at a time, thus guaranteeing the correctness of the data in multi-threaded situations.

The lock class is defined in the 5.hreading module, allowing for easy handling of locks:

# Create lock mutex = Threading. Lock ()#  locked mutex.acquire ()#  release mutex.release ()

6. For example, use a mutex to complete 2 threads each adding 1 million times to the same global variable

    ImportThreadingImportTime G_num=0deftest1 (num):GlobalG_num forIinchrange (num): Mutex.acquire ()#lockedG_num + = 1mutex.release ()#Unlock           Print("---test1---g_num=%d"%g_num)deftest2 (num):GlobalG_num forIinchrange (num): Mutex.acquire ()#lockedG_num + = 1mutex.release ()#Unlock            Print("---test2---g_num=%d"%g_num)#Create a mutex lock    #The default is an unlocked stateMutex =Threading. Lock ()#Create 2 threads and let them each add 1 million times to the G_numP1 = Threading. Thread (Target=test1, args= (1000000,)) P1.start () P2= Threading. Thread (Target=test2, args= (1000000,)) P2.start ()#wait for the calculation to complete     whileLen (Threading.enumerate ())! = 1: Time.sleep (1)Print("The end result of 2 threads after the same global variable operation is:%s"% g_num)

By adding a mutex, there is no competition for resources and results are incompatible with ideals.

Multitasking-Threading Basics and summary

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.