[event scheduler & thread] learning notes

Posted by rigbyae on Sun, 30 Jan 2022 14:11:40 +0100

event scheduler

Event scheduler: as the name suggests, it is mainly used to schedule events. In fact, for me, this is more like a timer. Too many explanations are not given here (the content itself is not complex, and no official explanation has been found for the time being. I'm afraid it will harm people's children). Directly on the code. Show the results.

function

sched = scheduler()  # Instantiate scheduler
sched.enter()  # Join event
sched.run()  # Run scheduler

code

# -*-coding: utf-8 -*-
import time


def GetTime():
    time_stamp = time.time()  # Get timestamp
    local_time = time.localtime(time_stamp)  # Time stamp to Beijing time
    return time.strftime("%Y-%m-%d %H:%M:%S", local_time)  # Beijing time to specific format


def SchedDisplay():
    from sched import scheduler

    def PrintTime(sched: scheduler):  # Scheduled events
        delay = 1  # Scheduling interval
        priority = 2  # priority
        sched.enter(delay=delay, priority=priority, action=PrintTime, argument=(sched,))  # Join event
        print("sched", GetTime())  # Beijing time to specific format

    sched = scheduler()  # Instantiate scheduler
    PrintTime(sched, )  # Scheduling events
    sched.run()  # Run scheduler


if __name__ == '__main__':
    SchedDisplay()

Explanation: first instantiate a scheduler sched, and then use sched in the PrintTime event Enter adds the event itself to achieve a circular scheduling effect, and finally uses sched Run() runs the scheduler

results of enforcement

sched 2021-06-09 18:22:58
sched 2021-06-09 18:22:59
sched 2021-06-09 18:23:00
sched 2021-06-09 18:23:01
...

thread

process

Process is the basic unit of resource (CPU, memory, etc.) allocation. It is an instance of program execution. When the program runs, the system will create a process and allocate resources for it, and then put the process into the process ready queue. When the process scheduler selects it, it will allocate CPU time for it, and the program starts to run.

thread

Thread is the smallest unit that the operating system can schedule operations. It is the basic unit of CPU scheduling and dispatching. Each thread has an independent stack and local variables.
For a single core CPU: multithreading is a CPU switching back and forth and executing alternately.
For multi-core CPU s: multithreading means that multiple execution paths are executed simultaneously (in parallel). If each core executes a thread, multiple cores may be executed at the same time.

Relationship between thread and process

Thread is included in the process and is the actual operation unit in the process. A process can be composed of many threads, and all resources of the process are shared among threads.
A running software (such as Xunlei) is a process. A process can run multiple tasks at the same time (Xunlei software can download multiple files at the same time, and each download task is a thread). You can simply think of a process as a collection of threads.

function

lock = threading.Lock()  # Apply for a lock
th = threading.Thread(target=fun, args=(param,))  # Instantiate thread
th.start()  # Start thread

Multithreaded code

# -*-coding: utf-8 -*-
import time


def GetTime():
    time_stamp = time.time()  # Get timestamp
    local_time = time.localtime(time_stamp)  # Time stamp to Beijing time
    return time.strftime("%Y-%m-%d %H:%M:%S", local_time)  # Beijing time to specific format


def ThreadDisplay():
    import threading

    lock = threading.Lock()  # Apply for a lock
    time_stamp = GetTime()  # Get timestamp
    thread_status = True

    def thread_1():
        nonlocal time_stamp  # Declare variable time_stamp is the variable defined by the upper layer
        while thread_status:
            with lock:  # Lock the shared data to prevent errors during simultaneous processing
                time_stamp = GetTime()

    def thread_2():
        times = 1
        nonlocal thread_status
        while thread_status:
            time.sleep(1)
            with lock:
                # Just use this variable, that is, read-only and not write. If it cannot be found locally, it will look for this variable from the outside according to a specific order.
                print("thread", time_stamp)
            times += 1
            if times > 3:
                thread_status = False

    th1 = threading.Thread(target=thread_1, args=())  # Instantiate thread
    th2 = threading.Thread(target=thread_2, args=())
    th1.start()  # Start thread
    th2.start()


if __name__ == '__main__':
    ThreadDisplay()

results of enforcement

thread 2021-06-09 18:23:23
thread 2021-06-09 18:23:24
thread 2021-06-09 18:23:25

Combination of scheduler and thread

code

# -*-coding: utf-8 -*-
import time


def GetTime():
    time_stamp = time.time()  # Get timestamp
    local_time = time.localtime(time_stamp)  # Time stamp to Beijing time
    return time.strftime("%Y-%m-%d %H:%M:%S", local_time)  # Beijing time to specific format


def SchedDisplay():
    from sched import scheduler

    def PrintTime(sched: scheduler):  # Scheduled events
        delay = 1  # Scheduling interval
        priority = 2  # priority
        sched.enter(delay=delay, priority=priority, action=PrintTime, argument=(sched,))  # Join event
        print("sched", GetTime())  # Beijing time to specific format

    sched = scheduler()  # Instantiate scheduler
    PrintTime(sched, )  # Scheduling events
    sched.run()  # Run scheduler


def ThreadDisplay():
    import threading
    th = threading.Thread(target=SchedDisplay, args=())  # Instantiate thread
    th.daemon = True
    th.start()  # Start thread


if __name__ == '__main__':
    ThreadDisplay()
    time.sleep(5)

results of enforcement

sched 2021-06-11 19:08:22
sched 2021-06-11 19:08:23
sched 2021-06-11 19:08:24
sched 2021-06-11 19:08:25
sched 2021-06-11 19:08:26

Topics: Python