threads, processes, and co-routines

Source: Internet
Author: User

One, thread (purpose to improve execution efficiency)

The smallest unit in the computer that performs a task

Pros: Create concurrent operations when sharing memory and IO operations

Cons: Seizing resources

Ii. process (Improve implementation efficiency)

A process is a dynamic execution of a program on a data set.

Advantage: Simultaneous use of multiple CPUs enables simultaneous operation of multiple operations

Cons: Consuming resources (re-opening up memory space)

Iii. the relationship between threads and processes

Threads are part of a process, threads run in process space, threads generated by the same process share the same memory space, and threads generated by the process are forced to exit and clear when the process exits. Threads can share all the resources owned by a process with other threads that belong to the same process, but they do not inherently have system resources and have only a bit of information that is essential in the run (such as program counters, a set of registers, and stacks).

1, the process is not the more the better, the number of CPUs = = Number of processes the best

2, the thread is not the more the better, concrete case specific analysis, (Request context switch time-consuming)

IO-intensive (no CPU)

Multithreading

Compute intensive (with CPU)

Multi-process

3. Global Interpreter Lock

# import threading# Import time# def f1 (num): #     Time.sleep (1) #     print (">>>%s"%num) #     return# for I in Range (Ten): #     t = Threading. Thread (target=f1,args= (i,), name= "t.%d"%i) #创造线程 #     T.start () # Print (a)
#当不用线程的时候, is single-threaded, each generated a number of CPUs to get one, sequentially output with the thread, the first to create multiple threads, each thread is responsible for generating a number, because the speed of the build thread is greater than the speed of the generation, the CPU randomly get the number generated, and then output, and the order of different

The code above creates 10 "foreground" threads, then the controller is handed over to the CPU,CPU according to the specified algorithm for scheduling, shard execution instructions

More ways:

T.start (): Activates thread,

T.getname (): Gets the name of the thread

T.setname (): Sets the name of the thread

T.name (): Gets or sets the name of the thread

T.is_alive (): Determines whether a thread is active

T.isalive (): Determines whether a thread is active

T.setdaemon () is set to either a background thread or a foreground thread (default: False), and a Boolean value that sets whether the thread is a daemon thread and must be used after the start () method is executed. If it is a background thread, during the main thread execution, the background thread is also in progress, after the main thread executes, the background thread will stop whether or not it succeeds or not; If the foreground thread is executing, the foreground thread is also in progress, and after the main thread executes, waiting for the foreground thread to finish executing, the program stops

T.isdaemon (): Determines whether it is a daemon thread

T.ident: Gets the identifier of the thread. The thread identifier is a non-0 integer that is valid only after the start () method is called, otherwise it only returns none.

T.join (): Executes each thread one by one, execution continues, and the method makes multithreading meaningless

T.run (): The Run method that automatically executes thread objects after a thread is dispatched by the CPU

Thread Lock

The biggest difference between multithreading and multi-process is that, in many processes, the same variable, each one copy is in each process, does not affect each other, and in many threads, all variables are shared by all threads, so any one variable can be modified by any one thread, so, The biggest danger of sharing data between threads is that multiple threads change a variable at the same time, and the content is scrambled.

Multithreading shares the same memory address of the resource, and the multi-process does not share

Import Threadingimport timeglobals_num = 0lock = Threading. Rlock () def Func ():    lock.acquire ()  # get lock    global globals_num    globals_num + 1    time.sleep (1)    Print (Globals_num)    lock.release ()  # Release lock for I in range (Ten):    t = Threading. Thread (Target=func)    T.start ()

If we want to make sure that the balance calculation is correct, we will give change_it() a lock, and when a thread starts executing change_it() , we say that the thread has acquired a lock, so the other thread cannot execute at the same time, change_it() wait until the lock is released, and then the lock can be changed. Since there is only one lock, no matter how many threads, at most one thread at a time holds the lock, so there is no conflict of modification. Creating a lock is done by threading.RLock()

The thread lock threading. Rlock and Threading.lock

When we use threads to manipulate data, if multiple threads modify a data at the same time, unpredictable results may occur, and in order to ensure the accuracy of the data, the concept of lock is introduced.

Rlock is allowed to be acquire multiple times in the same thread. But lock does not allow this situation. If you use Rlock, then acquire and release must appear in pairs, that is, call n times acquire, must call N-times release to really release the occupied

Threading. Event

Event is one of the most mechanisms of inter-thread communication: One thread sends an event signal, while the other threads wait for the signal. Used for the main thread to control the execution of other threads. Events manages a flag that can be set to true using Set () or reset to false,wait () using clear () to block, before flag is true. Flag defaults to False.

    • Event.wait ([timeout]): Blocks the thread until the event object's internal identity bit is set to true or timed out (if parameter timeout is provided).
    • Event.set (): Set the identity bit to ture
    • Event.clear (): Sets the identity companion to False.
    • Event.isset (): Determines whether the identity bit is ture.
Import Threading def do:    print (' start ')    event.wait ()    print (' execute ') Event_obj = threading. Event () for I in range:    t = Threading. Thread (Target=do, args= (Event_obj,))    T.start () event_obj.clear () InP = input (' input: ') if InP = = ' true ':    event_ Obj.set ()

When the thread executes, if flag is false, the thread blocks and the thread does not block when flag is true. It provides both local and remote concurrency.

Queue Module

threads, processes, and co-routines

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.