"Python" ThreadPool thread pool task Termination Simple example

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, ThreadPool
Import time
From multiprocessing import Process
Definition of exceptions and special values (0)
Class Finish (syntaxwarning):
Pass



Class Pauseinfo (syntaxwarning):
Pass


Pause_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.sleep (para)
Print (' Stop for ', para)
Return True

While 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 (10)
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 = []
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 would continue
Continue for 1
Continue for 1
Continue for 1
Continue for 1
Stop for 8
Input number list to test and any other word to quit

"Python" ThreadPool thread pool task Termination Simple example

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.