Multi-process and multi-thread

Source: Internet
Author: User

Multi-process and multi-thread

Multi-process and multi-thread

#! /Usr/bin/python #-*-coding: UTF-8-*-import osimport threadingimport multiprocessingimport time # Process entrydef process_worker (sign, lock, function): global count_process # lock. acquire () count_process + = 1 print (sign, OS. getpid () print apply (function) # lock. release () # Thread entrydef thread_worker (sign, lock, function): global count_thread lock. acquire () count_thread + = 1 print (sign, OS. getpid () print apply (function) lock. release () # real work functions def Lee (): return 'I am Lee' def Marlon (): return 'I am Marlon' def Allen (): return 'I am Allen' count_thread = 0count_process = 0if _ name __= = '_ main _': # Multi-process begin multiprocessing. freeze_support () # required in window python. Otherwise, many processes may be opened at will. print ('main: ', OS. getpid () record = [] lock = multiprocessing. lock () func_list = [Lee, Marlon, Allen] for function in func_list: process = multiprocessing. process (target = process_worker, args = ('process', lock, function) Process. start () record. append (process) for process in record: process. join () print "count_process value is", count_process # This value has not changed, and Multi-process does not share memory # Multi-thread begin record = [] lock = threading. lock () for function in func_list: thread = threading. thread (target = thread_worker, args = ('thread', lock, function) thread. start () record. append (thread) for thread in record: thread. join () print "count_thread value is", count_thread # This value is changed, so multi-thread shared memory

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.