Multi-threaded Python study notes

What is a thread?

Thread (English: thread) is the smallest unit of an operating system capable of operation scheduling. It is included in the process, the actual operation of the unit process. (Excerpt from Baidu Encyclopedia) resources are shared between threads

What is multi-threaded?

Multithreading (English: multithreading), means to achieve concurrent execution of multiple threads technology from the software or hardware. A computer with multi-threading capability due to hardware support and can execute more than one thread at the same time, thereby enhancing the overall processing performance (taken from Baidu Encyclopedia)

How to understand the multi-threaded?

Multi-process equivalent to our computer only open a browser, and open the music player. And some of the operations carried out by a multi-threaded equivalent in music player inside, as the song, pause.

How to achieve multi-threaded

python multithreading to achieve two modules: threadand threadingrarely, more inclined to the underlying operating, thread the module. We generally operate with threading module.
Here's what I used to write a small py2.7 Demo, to roughly analyze multi-threaded implementation and action.

# -*- coding: UTF-8 -*-
import threading

num = 1

def print_num(thread_name,num):
    while num<=20:
        print "%s:%d"%(thread_name,num)
        num+=1


try:
    t1 = threading.Thread(target=print_num,args=("Thread1",num))
    t2 = threading.Thread(target=print_num,args=("Thread2",num))
    t1.start()#开始线程1
    t2.start()#开始线程2
except:
    print "something error!"

Create a function of the need to use multiple threads to threading.Thread(). In which the target parameter is the name of the function requires multiple threads of execution, args parameter to perform the function of the need to pass parameters
then start()to begin execution.
Let's look at the results:
Here Insert Picture Description
you can see, though not quite time to start threads 1 and 2, but still you can see there are some common threads running time of two functions print_num, usually need to run two functions need to function on a to conduct a call the next run is completed, and multi-threading allows them simultaneously. If you want it at the same time numcarry out operations, simply numvariable to a global variable.

What is daemon

For the experiment, the main thread after the end of the two sub-thread to wait until the end. If you want the main thread ends directly, you can use setDaemon(True)set Daemon thread begins before the child, such as the following:

# -*- coding: UTF-8 -*-
import threading

num1 = 1

def print_num(thread_name):
    global num1
    while num1<=1000://注意这里的停止范围
        num1 += 1
        print thread_name+":"+str(num1)

try:
    t1 = threading.Thread(target=print_num,args=("Thread1",))
    t2 = threading.Thread(target=print_num,args=("Thread2",))
    t1.setDaemon(True)//设置守护进程
    t2.setDaemon(True)
    t1.start()
    t2.start()
except:
    print "something error!"

The result is:
Here Insert Picture Description
you can see, although I set num1 added to the end of 1000, but in fact num added 18 over.

What is a mutex? What is the use?

Dirty data can occur when multiple threads modify the same data at the same time: the previously mentioned resources are shared between threads, which creates a problem. For example:
There are two threads t1, t2, and a global variable a, t1 and t2 are performed simultaneously on a 1-1 + operation. A look seems to have no changes, but when the operation proceeds to + t1 and t2 at the same time, a value sometimes becomes 3 , at this time if you are using a data problems may occur.
In this case, we need a mutex, t1, when operating a lock, can not be modified so that a t2, t1, etc. and then released once the complete operating
code is as follows:

# -*- coding: UTF-8 -*-
import threading

num1 = 1
lock = threading.Lock()

def print_num(thread_name):
    global num1

    while True:
        num1+=1
        num1-=1
        if num1 == 3:
            print thread_name+":"+str(num1)
            exit(0)

def run_thread(thread_name):
    lock.acquire()//获取锁
    try:
        print_num(thread_name)
    finally:
        lock.release()//释放锁
try:
    t1 = threading.Thread(target=run_thread,args=("Thread1",))
    t2 = threading.Thread(target=run_thread,args=("Thread2",))
    t1.start()
    t2.start()
except:
    print "something error!"

At this point no longer run on this issue.

Recursive lock and asynchronous have not read a later update

Reference article:
https://www.liaoxuefeng.com/wiki/1016959663602400/1017629247922688

Published 37 original articles · won praise 2 · Views 1419

Guess you like

Origin blog.csdn.net/weixin_44377940/article/details/104864149