Key points analysis of thread pool

Source: Internet
Author: User

Key points analysis of thread pool

1. Consider establishing the number of threads

2. The status of the thread pool

    With open (' flog ') as F:
F.write ()

3. Close the thread

Instance (simple instance)

Principle:

1: Create 10 thread objects
2:queue the queue to fetch the thread. Available: take; otherwise: wait
3: Thread execution is complete and returned to the thread pool
#!/usr/bin/env python# coding:utf-8import  queueimport Threading "" "1: Create 10 thread objects 2:queue queue fetch thread. Available: take; otherwise: Wait 3: Thread execution complete, return to thread Pool "" "Class ThreadPool (object):    # Set a default parameter Max_num    def __init__ (self,max_num=20):        # Create        a queue Self.queue = Queue.queue (max_num)        # Loop Create 1 objects for        i in Xrange (max_num):            self.queue.put ( Threading. Thread)    def get_thread (self):        return Self.queue.get ()    # Use the class    def add_thread (self):        Self.queue.put (Threading. Thread) # Create object # create 1 queue with up to 10 threads pool = ThreadPool (+) def func (arg,p):    print arg import time    time.sleep ( 2)    P.add_thread () # 300 tasks to execute for i in xrange:    # Gets a thread, thread    = Pool.get_thread ()    # executes this thread    t = Thread (target=func,args= (i,pool))    T.start ()

Example (Twisted.python.threadpool)

#!/usr/bin/env python# coding:utf-8import  contextlibdoing = [] @contextlib. Contextmanagerdef Show (Li,item):    # print "Before"    doing.append (item)    yield    doing.remove (item) print Len (doing) with show (doing,1):    print ' with '    print len (doing) print Len (doing)

Key points analysis of thread pool

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.