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"); } }
相关文章推荐
- python多线程、异步、多进程+异步爬虫
- python多进程与多线程之间的联系
- Python的多线程(threading)与多进程(multiprocessing )
- Python的多线程/多进程
- python的多进程和多线程
- Python中的多进程与多线程(一)
- SAE中Python无法创建多线程的解决方案
- Python多线程与多进程
- 【Python】多线程 & 多进程(1)
- 测试Python多线程与多进程
- python【第九篇】多线程、多进程
- python多进程与多线程学习总结
- Python 多线程多进程10.4.1 应用于自动化测试项目
- Python创建多进程,用Queue传递信息
- Python之多进程、多线程、协程和分布式进程
- 为什么在Python里推荐使用多进程而不是多线程?
- Python多线程与多进程
- 为什么在Python里推荐使用多进程而不是多线程?
- Python之多进程多线程
- python基础-Process创建进程、join方法、实现ftp多进程