Multithreading -01

Multithreading

Processes and Threads

process

The essence of the process is to run a program of (abstraction)

The smallest resource unit (operating system allocates cpu, the basic unit of memory resources)

Thread

The minimum basic unit of execution units (instance), is scheduled and dispatched cpu

Each thread has its own stack and local variables

1. A program has at least one process, a process has at least one thread. (Process can be understood as a container thread), a process where you can open multiple threads and processes

2. The process has a separate memory unit in the implementation process, and multiple threads share the memory of this process, thereby greatly enhancing the efficiency of the program

3. A thread (the main thread to create child threads) can be created and destroyed another thread; can execute concurrently across multiple threads in the same process

Concurrency & Parallel

Concurrency: The system has the ability to handle multiple tasks, cpu mad switch (monocytes)

Parallel: The system includes the ability to process multiple tasks simultaneously (multi-core)

Synchronous Asynchronous

Sync: I cook, I cooked rice to cooking, etc. - and so

Asynchronous: the course of my cooking, you can go to cooking - ranging

GIL lock python interpreter

No matter how many threads you start, you have a number of cpu, Python will be in the implementation of calm at the same time allowing only one thread to run

A python process at the same time only one thread can call the cpu (multi-check it basically useless)

But can open multiple processes and each process can have a thread threw a cpu, be implemented in parallel

Compute-intensive: high-efficiency multi-process

I / O-intensive: high-efficiency multi-threaded (IO process cpu will have free time, you can take advantage of free time to do other tasks)

Or multi-threaded (multi-process + Ctrip) for IO-intensive, such as socket, reptiles, web

Multi-process for compute-intensive, such as financial analysis (but not recommended)

python multithreading

Example 1

There are the following three threads, a main thread, the main thread has opened up two sub-thread

The first main thread has finished running, t1 child threads run 3 seconds, t2 child thread running 6 seconds

The whole process took a little over six seconds End

import threading
import time

def zx(t,s):
    time.sleep(s)
    print(t)


if __name__ == '__main__':
    t1=threading.Thread(target=zx,kwargs={"t":"t1","s":3})
    t1.start()

    t1=threading.Thread(target=zx,kwargs={"t":"t2","s":6})
    t1.start()

    print("main")

main
t1
t2

Process finished with exit code 0
例2

As above point of knowledge

import time
import threading

def music():
    print("开始听歌")
    time.sleep(3)
    print("停止听歌")

def game():
    print("开始玩游戏")
    time.sleep(6)
    print("停止玩游戏")

if __name__ == '__main__':
    t1=threading.Thread(target=music)
    t2=threading.Thread(target=game)
    t1.start()
    t2.start()

    print("main")

Songs began
to play the game
main
stop listening to music
to stop playing games

Process finished with exit code 0

Common method

# run():  线程被cpu调度后自动执行线程对象的run方法
# start():启动线程活动。
# isAlive(): 返回线程是否活动的。
# getName(): 返回线程名。
# setName(): 设置线程名。

threading模块提供的一些方法:
# threading.currentThread(): 返回当前的线程变量。
# threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
# threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

join () thread waits

join (): Before the child thread finishes running, the parent of the child thread thread will be blocked.

The following codes are read before the culmination

join () corresponds, after executing the sub-thread, the main thread executed again following code

import time
import threading

def music():
    print("开始听歌")
    time.sleep(3)
    print("停止听歌")

def game():
    print("开始玩游戏")
    time.sleep(6)
    print("停止玩游戏")

if __name__ == '__main__':
    t1=threading.Thread(target=music)
    t2=threading.Thread(target=game)
    t1.start()

    t1.join()

    t2.start()

    t2.join()

    print("main")

Start listening to music
stops songs
start playing the game
to stop playing games
main

Process finished with exit code 0

setDaemon () daemon threads

setDaemon(True):

The thread is declared as a daemon thread, must () method is called before setting the start, when we run the program, the implementation of a main thread, the main thread has finished running, want to quit, it will test whether the child thread to complete. If the child thread is not completed, the main thread will wait for the child threads to complete before exit. But sometimes we need is just the main thread finishes, regardless of whether the child thread to complete, and should be the main thread exits together, then you can setDaemon method it

Example 1

When the main thread has finished running, to test t1 and t2, we found that they are daemon thread exit

import time
import threading

def music():
    print("开始听歌")
    time.sleep(3)
    print("停止听歌")

def game():
    print("开始玩游戏")
    time.sleep(6)
    print("停止玩游戏")

if __name__ == '__main__':
    t1=threading.Thread(target=music)
    t2=threading.Thread(target=game)
    t1.setDaemon(True)
    t2.setDaemon(True)
    t1.start()
    t2.start()
    print("main")

Songs began to
play the game
main

Process finished with exit code 0

Example 2

When the main thread has finished running, to test t1 and t2, t1 found not daemon thread is a daemon thread t2, t1 took 3 seconds t1 finished, exit, because t2 takes 6 seconds or daemon thread, the main thread and leave it

import time
import threading

def music():
    print("开始听歌")
    time.sleep(3)
    print("停止听歌")

def game():
    print("开始玩游戏")
    time.sleep(6)
    print("停止玩游戏")

if __name__ == '__main__':
    t1=threading.Thread(target=music)
    t2=threading.Thread(target=game)
    t2.setDaemon(True)
    t1.start()
    t2.start()
    print("main")

Songs began
to play the game
main
stop listening to music

Process finished with exit code 0

Guess you like

Origin www.cnblogs.com/zx125/p/11440563.html
01