Python multithreading-threading and thread synchronization, timing scheduling (timing tasks)

Compared with _thread, threading has a higher degree of encapsulation and function expansion, which is more simple and convenient for users.

import threading,time
# 蒂尼多
def thread_handle(delay):
    for num in range(10):
        # 追加一个延时操作
        time.sleep(delay);
        print("{},num = {}".format(threading.currentThread().name,num));

def main():
    for item in range(10):
        # 创建一个新的线程对象,设置好该线程对象的处理函数以及参数内容,并且配置好线程名称
        thread = threading.Thread(target=thread_handle,args=(1,),name="执行线程 - {}".format(item))
        thread.start();
    time.sleep(200);

if __name__ == '__main__':
    main();

The number of active threads for printing will be 11, one main thread, and 10 child threads

import threading,time
# 蒂尼多
def thread_handle(delay):
    for num in range(10):
        # 追加一个延时操作
        time.sleep(delay);
        print("{},num = {}".format(threading.currentThread().name,num));

def main():
    for item in range(10):
        # 创建一个新的线程对象,设置好该线程对象的处理函数以及参数内容,并且配置好线程名称
        thread = threading.Thread(target=thread_handle,args=(1,),name="执行线程 - {}".format(item))
        thread.start();
    time.sleep(1);
    print("主线程ID:{},主线程名称:{}".format(threading.current_thread().ident, threading.current_thread().name));
    print("当前活跃线程个数:{}".format(threading.active_count()));
    print("当前活跃线程信息:{}".format(threading.enumerate()));
if __name__ == '__main__':
    main();

Use an object-oriented approach to multithreading

import threading,time
class MyThread(threading.Thread):
    def __init__(self,thread_name,delay):
        # 将线程名字传递到父类构造
        super().__init__(name = thread_name);
        # 保存延迟时间
        self._delay = delay;
    def run(self):
        for num in range(5):
            # 线程执行延迟
            time.sleep(self._delay);
            print("{},num = {}".format(threading.current_thread().getName(),num));

def main():
    for item in range(10):
        # 创建一个新的线程对象,设置好该线程对象的处理函数以及参数内容,并且配置好线程名称
        thread = MyThread("执行线程:{}".format(item),1)
        thread.start();
if __name__ == '__main__':
    main();

Thread synchronization

import threading,time

# 定义银行的处理业务
def bank_handle(semaphore):
    # 尝试获取信号量,如果没有获取就等待
    if semaphore.acquire():
        print("{},资源抢占成功,开始办理个人相关业务".format(threading.current_thread().name));
        # 模拟业务办理时间
        time.sleep(2);
        # 释放锁定
        semaphore.release();

def main():
    semaphore = threading.Semaphore(2);
    thread_list = [threading.Thread(target=bank_handle,args=(semaphore,),name="银行客户:{}".format(item)) for item in range(10)];
    for item in thread_list:
        item.start();

if __name__ == '__main__':
    main();

Python's traditional thread synchronization mechanism uses Lock to lock, but if repeated locks are not unlocked, deadlocks will occur. In order to solve this problem, Python provides RLock. The advantage of this is that no matter how many times the lock is added, it can be used once. Sex unlock;

import threading,time
ticket = 3;
# 定义银行的处理业务
def sale(lock):
    # 尝试获取信号量,如果没有获取就等待
    if lock.acquire():
        global ticket;
        if ticket > 0:
            time.sleep(1);
            ticket -= 1;
            print("{}卖票,剩余票数为:{}".format(threading.current_thread().name,ticket));
        # 释放锁定
        lock.release();

def main():
    lock = threading.RLock();
    thread_list = [threading.Thread(target=sale,args=(lock,),name="银行客户:{}".format(item)) for item in range(10)];
    for item in thread_list:
        item.start();

if __name__ == '__main__':
    main();

Timing scheduling

import threading,time,sched
ticket = 3;
# 定义银行的处理业务
def event_handle(schedule):
    print("{}奥特曼".format(threading.current_thread().name));
    # delay延迟1秒,priority优先级,action执行函数,argument传递参数
    schedule.enter(delay=1,priority=0,action=event_handle,argument=(schedule,));

def main():
    # 创建定时调度
    schedule = sched.scheduler();
    schedule.enter(delay=0,priority=0,action=event_handle,argument=(schedule,));
    schedule.run();

if __name__ == '__main__':
    main();

Guess you like

Origin blog.csdn.net/weixin_44887276/article/details/114870504