睡眠排序python多线程多进程实现

睡眠排序python多线程多进程实现

直接先上代码


# -*- coding: utf-8 -*-
# CopyRight by heibanke
import time
import random
from threading import Thread
from multiprocessing import Process
def sleepsort(n):
    time.sleep(n*0.1)
    print n,"--",

def thread_process_job(n, Thread_Process, job, value):
    local_time=time.time()
    threads_or_processes = [Thread_Process(target=job,args=(value[i],)) for i in xrange(n)]
    for t in threads_or_processes:
        t.start() 
    for t in threads_or_processes:
        t.join() 

    print n,Thread_Process.__name__," run job need ",time.time()-local_time

if __name__=="__main__":
    sort_list = [random.randint(1,40) for i in xrange(10)]
    print "Multi Threads"
    for i in xrange(5):
        sort_list = [random.randint(1,40) for i in xrange(10)]
        thread_process_job(len(sort_list),Thread, sleepsort, sort_list)

    print "Multi Process"
    for i in xrange(5):
        sort_list = [random.randint(1,40) for i in xrange(10)]
        thread_process_job(len(sort_list),Process, sleepsort,sort_list)

比较搞笑的睡眠排序算法。看网上的文章里没写Python版本的,将用Python做些事的课程示例代码giltest0.py修改一下即可实现。

运行看看能否达到排序的效果,修改修改sleep的睡眠参数看看效果是否有所变化。理解一下为什么。分享一下你的理解吧。