zoukankan      html  css  js  c++  java
  • Python多进程

    用win api写程序的时候,多进程的程序基本没写过,因为多线程已经能够满足大部分需要。

    但是python的多线程有个问题,进程内的线程都是共享一个CPU核心的,类似于单线程的时间分片。以前写的时候记得这个问题处理起来难度还挺大,后来就没再搞了。

     1 from multiprocessing import Process
     2 import os
     3 
     4 def run_proc (name):
     5     print 'Run child process is %s, pid = %d' % ( name, os.getpid() )
     6 
     7 if __name__ == '__main__':
     8     print 'Run Parent process pid is = %d' % os.getpid()
     9     SecondProcess = Process ( target = run_proc, args = ('test', ) )
    10     print 'starting Second process'
    11     SecondProcess.start()
    12     print 'Child process end'

    参照廖雪峰上教程写的一个多进程程序,能同时运行2个进程,然后退出。

     1 from multiprocessing import Process
     2 import os
     3 
     4 def run_proc (name):
     5     print 'Run child process is %s, pid = %d' % ( name, os.getpid() )
     6     val = 0;
     7     while 1:
     8         val += 1
     9 
    10 if __name__ == '__main__':
    11     print 'Run Parent process pid is = %d' % os.getpid()
    12     SecondProcess = Process ( target = run_proc, args = ('test', ) )
    13     print 'starting Second process'
    14     SecondProcess.start()
    15     val = 0;
    16     while 1:
    17         val += 1
    18     print 'Child process end'

    然后在两个进程文件中添加死循环的代码,看下CPU的使用情况:

    可以看到,同时运行的2个线程是分占处理器的,能够充分发挥硬件的性能。

  • 相关阅读:
    洛谷 P1019单词接龙
    洛谷 P1091合唱队列
    洛谷 P1141 01迷宫
    洛谷 P1101单词方阵
    NOIP要炸?
    洛谷 P1219八皇后
    洛谷 P1181数列分段Section I
    刷普及-刷爆了。。。。。。
    洛谷 P3952时间复杂度 (本地AC测评RE的伪题解)
    动态数码管
  • 原文地址:https://www.cnblogs.com/matrix-r/p/6979356.html
Copyright © 2011-2022 走看看