python创建多进程_python创建多进程/多线程

#!/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");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值