python创建多进程/多线程

来源:互联网 发布:agv导航算法 编辑:程序博客网 时间:2024/05/21 06:53
#!/usr/bin/pythonimport os, timeprint "Before the fork, my PID is", os.getpid()if os.fork():    print "I am the parent, my PID is", os.getpid()else:    print "I am the child, my PID is", os.getpid()time.sleep(2)print "Hello from both of us"
运行结果如下
root # ./server.pyBefore the fork, my PID is 3161I am the child, my PID is 3162I am the parent, my PID is 3161Hello from both of usHello from both of us
子进程终止时,需要调用wait函数,不然系统资源会被大堆zombie进程消耗掉。子进程结束时会发出SIGCHLD信号,用信号解决zombie或者poll轮询
os.fork需要在支持fork函数的系统中运行。
import threading, timeimport sysdef threadcode(count):    sys.stdout.write("I am the new thread %s\n" %                     threading.currentThread().getName())    time.sleep(count)newThread = threading.Thread(target = threadcode, name = "ChildThread" , args = [2])newThread.setDaemon(1)newThread.start()sys.stdout.write("I am the main thread %s\n" %                 threading.currentThread().getName())time.sleep(2)newThread.join()
为了在多个线程之间共享资源,可以引入锁,信号量等机制。用线程机制可以轻松地编写支持多个并发的服务器端。

关于异步IO的资料参照Python网络编程基础相关章节

java线程创建方式如下:

一,Thread创建线程package com.ciaos;public class Test extends Thread {public void run(){System.out.println("thread start");try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("thread end");}public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("main start");Thread a = new Test();a.start();System.out.println("main end");}}二,Runnable接口创建线程package com.ciaos;public class Test implements Runnable {public void run(){System.out.println("thread start");try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("thread end");}public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("main start");Runnable rb = new Test();Thread a = new Thread(rb);a.start();System.out.println("main end");}}


原创粉丝点击