zoukankan      html  css  js  c++  java
  • python进程与线程的操作

    进程操作:

    # project  :Python_Script
    # -*- coding = UTF-8 -*-
    # Autohr   :XingHeYang
    # File     :processTest.py
    # time     :2019/11/5  16:00
    # Describe :进程操作
    # ---------------------------------------
    from multiprocessing import Process   # 导包
    import time
    
    def run(process_name):  #设计需要以进程执行的函数
        i = 0
        while i <= 5:
            print('进程 %s 执行:------>'%process_name)
            time.sleep(2)
            i += 1
    
    
    
    if __name__ == '__main__':
        print('父进程开始')
    
        #创建进程对象,target需要传入的是需要以进程执行的函数名。
        # args需要以元组的形式传入执行函数的参数,如果只有一个参数也需要以元组的形式传入
        p1 = Process(target=run, args=('第一个',))
        p2 = Process(target=run, args=('第二个',))
        p3 = Process(target=run, args=('第三个',))
        #启动进程,并打印出进程id
        p1.start()
        print('p1进程id:',p1.pid)
        p2.start()
        print('p2进程id:',p2.pid)
        p3.start()
        print('p3进程id:',p3.pid)
        #子进程等待父进程结束后结束
        p1.join()
        p2.join()
        p3.join()
    
        print('父进程结束')

    线程操作:

    # project  :Python_Script
    # -*- coding = UTF-8 -*-
    # Autohr   :XingHeYang
    # File     :Thread_Test.py
    # time     :2019/11/5  16:28
    # Describe :python 线程操作
    # ---------------------------------------
    #Content:线程:在python中有两个模块(_thread(低级的线程模块:表示的越接近底层),
    # threading(高级的线程模块),threading相当于对_thread又进行了一次封装)
    
    from threading import Thread
    import time
    
    def run(process_name):
        i = 0
        while i <= 10:
            print('线程 %s 执行:------>'%process_name)
            time.sleep(2)
            i += 1
    if __name__ == '__main__':
        print('进程开始')
    
        #创建线程对象,传入的参数意义和进程相同
        p1 = Thread(target=run, args=('第一个',))
        p2 = Thread(target=run, args=('第二个',))
        p3 = Thread(target=run, args=('第三个',))
        #启动线程
        p1.start()
        p2.start()
        p3.start()
        #子线程等待父线程结束后结束
        p1.join()
        p2.join()
        p3.join()
    
        print('进程结束')
  • 相关阅读:
    Balance的数学思想构造辅助函数
    1663. Smallest String With A Given Numeric Value (M)
    1680. Concatenation of Consecutive Binary Numbers (M)
    1631. Path With Minimum Effort (M)
    1437. Check If All 1's Are at Least Length K Places Away (E)
    1329. Sort the Matrix Diagonally (M)
    1657. Determine if Two Strings Are Close (M)
    1673. Find the Most Competitive Subsequence (M)
    1641. Count Sorted Vowel Strings (M)
    1679. Max Number of K-Sum Pairs (M)
  • 原文地址:https://www.cnblogs.com/XhyTechnologyShare/p/11799628.html
Copyright © 2011-2022 走看看