[Python] multi-thread threading Function Method-computing 5! + 4! + 3! + 2! + 1!

Source: Internet
Author: User

The last time I used a row of functions, I used multiple threads.

# Coding = utf8''' def singles (): Sum = 0 for I in range (): t = reduce (lambda X, Y: x * y, range (1, I + 1) sum + = t return sum print singles () ''' # multi-threaded implementation, start five threads at once to calculate the factorial from 1 to 5, A global variable sum adds the result to import threading, time sum = 0 lock = threading. lock () def single (I): global sum, lock. acquire () t = reduce (lambda X, Y: x * y, range (1, I + 1) sum = sum + T print threading. currentthread (). getname (), t lock. release () def main (): global sum for I in range (1, 6): threading. thread (target = single, argS = (I,), name = 'thread' + STR (I )). start () time. sleep (1) print sum if _ name __= = '_ main _': Main ()

Without judging thread blocking, it is not safe to use sleep directly.

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.