您的位置:首页 > 编程语言 > Python开发

python创建多进程/多线程

2013-01-05 08:31 351 查看
#!/usr/bin/python

import os, time

print "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.py
Before the fork, my PID is 3161
I am the child, my PID is 3162
I am the parent, my PID is 3161
Hello from both of us
Hello from both of us
子进程终止时,需要调用wait函数,不然系统资源会被大堆zombie进程消耗掉。子进程结束时会发出SIGCHLD信号,用信号解决zombie或者poll轮询

os.fork需要在支持fork函数的系统中运行。

import threading, time
import sys

def 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 block
e.printStackTrace();
}
System.out.println("thread end");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.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 block
e.printStackTrace();
}
System.out.println("thread end");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("main start");
Runnable rb = new Test();
Thread a = new Thread(rb);
a.start();
System.out.println("main end");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: