Python ---- Thread 1

Theoretical knowledge 1. thread

  1. What is the thread

    Thread is a pipeline.

    What is the process? Process has been started experiencing what?

    Open process: open space in memory, loading resources and data calls cpu execution, may also use the resources of this space.

    Process: The main task: open space, load the data.

    Thread: pipeline, executing code.

1563953708745

Process: division of space, static load resources.

Thread: Code execution capability, dynamic.

Abstract concept.

Open qq: open a process: in memory, open space, data is loaded to start a thread to execute code.

A thread is dependent on the process, a process can contain multiple threads, but there must be a main thread. Cpu thread is the smallest unit of execution.

  1. Thread vs Process (theory)

    1. Open multi-process overhead is very large. 10-100. Turn threads overhead is very small.

    2. Open multi-process slow, fast multi-threaded open.

    3. Process data can not be directly between the queues can be shared via data between threads in the same process can be shared.

  2. Multi-threaded application scenarios Introduction

    Concurrency: a cpu switch back and forth (to switch between threads) concurrent multi-process, multi-threaded concurrency.

    More complicated process: open multiple processes, each process main thread to perform tasks inside.

    Multithreading: open a process, the process which multiple threads execute tasks.

    When using multi-process, when to use multithreading?

    A program: three different tasks.

    If the later work experience concurrency: Multithreaded majority.

2. Open thread in two ways

# 第一种方式
from threading import Thread
def task(name):
     print(f'{name} is running')
if __name__ == '__main__':
    t = Thread(target=task,args=('mcsaoQ',))
    t.start()
    print('主线程')
#第二种方式
from threading import Thread
class MyThread(Thread):
    def run(self):
        print(f'{self.name} is running')
if __name__ == '__main__':
    t = MyThread()
    t.start()
    print('主线程')

3. The contrast between threads and processes

  1. Contrast speed

    from threading import Thread
    def task(name):
        print(f'{name} is running')
    if __name__ == '__main__':
        t = Thread(target=task,args=('mcsaoQ',))
        t.start()
        print('主线程')
    '''
    线程绝对要比进程要快:
        mcsaoQ is running
        主线程
    '''
  2. pid

    # pid 进程号
    from threading import Thread
    import os
    def task():
        print(f'子线程: {os.getpid()}')
    if __name__ == '__main__':
        t = Thread(target=task,)
        t.start()
        print(f'主线程: {os.getpid()}')
  3. Sharing resources between threads

    from threading import Thread
    import time
    x = 1000
    def task():
         time.sleep(3)
         print('子线程....')
    def main():
         print('111')
         print('222')
         print('333')
    if __name__ == '__main__':
         t = Thread(target=task)
         t.start()
         # t.join()
         main()

4. Other threads

from threading import Thread
import threading
import time
def task(name):
     time.sleep(1)
     print(f'{name} is running')
     print(threading.current_thread().name)
if __name__ == '__main__':
     for i in range(5):
         t = Thread(target=task,args=('mcsaoQ',))
         t.start()
     # 线程对象的方法:
     # time.sleep(1)
     # print(t.is_alive())  # 判断子线程是否存活  ***
     # print(t.getName())  # 获取线程名
     # t.setName('线程111')
     # print(t.getName())  # 获取线程名
     # threading模块的方法:
     # print(threading.current_thread().name)  # MainThread
     # print(threading.enumerate())  # 返回一个列表 放置的是所有的线程对象
     print(threading.active_count())  # 获取活跃的线程的数量(包括主线程)
     print('主线程')

5. daemon thread

Guardian: Child Guardian Lord, as long as the main end, sub-end immediately.
The main thread when the end ???
Multithreading is the same space, the same process, the process on behalf of space, resources static main thread is in the process space memory alive. the necessary conditions.
the main thread: have to wait for all of the child threads all over after you're finished, the process of disappearing.
daemon thread must wait for the main thread to finish before the end of the main thread must wait for all non-daemon thread end to end .
daemon thread: the end of all non-daemon threads and the main thread must wait to be able to end.

from threading import Thread
import time
def foo():
    print(123)
    time.sleep(3)
    print("end123")
def bar():
    print(456)
    time.sleep(1)
    print("end456")
if __name__ == '__main__':
    t1=Thread(target=foo)
    t2=Thread(target=bar)
    t1.daemon = True
    t1.start()
    t2.start()
    print("main-------")

6. mutex (lock)

Mutex lock, synchronization lock is a lock.

Mutex and differences join?

Mutex lock to grab random and fair. Join in advance in good order, unfair, but are serial.

1563953747387

7. deadlock, recursive lock

Recursive lock: recursive lock is a lock, the lock record, acquire a long, locked to count 1, acquire2 times, 2 times locked to count, Release1 times, minus one, as long as the lock recursion counter is not 0, other threads can not grab.

from threading import Thread
from threading import Lock
from threading import RLock
import time
# lock_A = RLock()
# lock_B = RLock()
lock_A = lock_B = RLock()
class MyThread(Thread):
    def run(self):
        # lock_A.acquire()
        # lock_B.acquire()
        # print(111)
        # lock_A.release()
        # lock_B.release()
        self.f1()
        self.f2()
    def f1(self):
        lock_A.acquire()
        print(f'{self.name}拿到 A锁')
        lock_B.acquire()  # 第二个线程抢B锁
        print(f'{self.name}拿到 B锁')
        lock_B.release()
        lock_A.release()
    def f2(self):
        lock_B.acquire()
        print(f'{self.name}拿到 B锁')
        time.sleep(1)  # 第一个线程 睡1秒
        lock_A.acquire()  # 第一个线程抢A锁
        print(f'{self.name}拿到 A锁')
        lock_A.release()
        lock_B.release()
if __name__ == '__main__':
    # for i in range(3):
    #     t = MyThread()
    #     t.start()
    t1 = MyThread()
    t1.start()
    t2 = MyThread()
    t2.start()
    t3 = MyThread()
    t3.start()
    print('主线程')

8. semaphore

Speaking before the lock is allowing only one thread or process to enter the semaphore allows multiple threads or processes simultaneously enter

from threading import Thread
from threading import current_thread
from threading import Semaphore
import time
import random
sm = Semaphore(4)
# lock= Lock()
def go_public_wc():
    sm.acquire()
    print(f'{current_thread().name}正在厕所')
    time.sleep(random.randint(1, 3))
    sm.release()
if __name__ == '__main__':
    for i in range(20):
        t = Thread(target=go_public_wc)
        t.start()
    # print('主')

Guess you like

Origin www.cnblogs.com/hql1117/p/11239545.html