Detailed description of the ThreadPool thread pool task termination sample code in Python

Source: Internet
Author: User

Demand

Join we need to deal with a string of single digits (0~9), an odd number of the need to cycle print it, even the number of waiting for the time to complete all tasks; 0 is an error, but you do not need to terminate the task, you can customize some processing.

Key points

Defining the Func function processing requirements

The callback handles the returned results, with only an even number and 0 return; the odd number is always executed; To control the thread pool state, you need to throw an exception for even and 0, and catch exception handling.

ThreadPool Defining thread pool concurrency

Realize

#-*-Coding:utf-8-*-from threadpool import makerequests, threadpoolimport timefrom multiprocessing import Process

Definition of exceptions and special values (0)

Class Finish (syntaxwarning):    Pass
Class Pauseinfo (syntaxwarning):    passpause_num = 0

Func function definition

0 o'clock returns false, other even numbers return true

def func (para):    if para = = Pause_num:        print (' Start for%d and wait%ds '% (para, 4))        Time.sleep (4)        print (' Error BCS ', para)        return False    if para% 2 = = 0:        print (' Start for%d and wait%ds '% (Para, para))        TIME.SL EEP (para)        print (' Stop for ', para)        return True when    true:        print (' Continue for ', para)        Time.sleep (para)

Callback definition

DEF callback (request, result):    if result:        raise Finish    else:        raise Pauseinfo

Thread pool Processing

Finish identification task completed, again induce abnormal exit thread pool processing;

def Main_thread (paras):    pool = ThreadPool (Ten)    requests = Makerequests (Callable_=func, Args_list=paras, Callback=callback)    [Pool.putrequest (req) for req in requests] while    True:        try:            pool.wait ()        Except Finish as E:            raise Systemexit        except Pauseinfo as E:            print (' Pause BCS%d but would continue '% pause_num )        except Exception as E:            print (' Unknown error so would quit ')            raise Systemexit

The main function plays a test process

If name = = ' main ': While    True:        s = input (' Input number list to test and any other word to quit\n ')        paras = []< C3/>for para in S:            if Para.isnumeric ():                paras.append (INT (para))            else:                break        try:            Thread_ Test = Process (Target=main_thread, Args= (paras,))            Thread_test.start ()            thread_test.join (timeout=20)        except Timeouterror as E:            print (' Task timeout ')        except Exception as E:            print (' Unknow error: ', e)

Result validation

Processing 108, look at the print can see, 1 is circulating processing, 0 processing time error; 8 processing completes the task ends

Input number list to test and any other word to quit
108
Continue for 1
start for 0 and wait 4s
start for 8 And wait 8s
continue for 1
continue for 1
continue for 1
Error BCS 0
continue for 1
Pause BCS 0 but wil L Continue
Continue for 1
Continue-1
Continue for 1
continue for 1
stop for 8
Input number list to T EST and any other word to quit

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.