当前位置: 首页 > 后端技术 > Python

睡眠排序——没有什么是睡眠解决不了的

时间:2023-03-25 21:17:13 Python

新年快乐!前几天看到一段js代码。const原始=[3,1,15,2,9,6,3,2,7,1]const结果=[]原始。forEach(n=>setTimeout(()=>result.push(n),n))上面的代码使用了setTimeout()函数。对于待排序的数组,它根据不同的值在不同的线程中休眠不同的时间,并压入结果实现排序。这种排序算法称为“睡眠排序”。尝试用Python写一个多线程的程序来玩玩。importtime,threadingoriginal=[3,1,15,2,9,6,3,2,7,1]result=[]#storethreadinstancelistpool=[]#appenddefsleepSort(num):timeaftersleep.sleep(num)result.append(num)#createmultiplethreadsforiinrange(len(original)):t=threading.Thread(target=sleepSort,args=(original[i],))pool.append(t)fortinpool:t.start()fortinpool:t.join()print(result)我把它作为time.sleep()的参数,没有对源数据做任何处理,所以这次是花了,嘿嘿,娱乐挺好的。另外threading模块中还有一个Timer类。它的第一个参数接收一个值,该值是指定的计时时间。剩下的地方和Thread一样,时间到后调用要执行的函数。.修改的代码如下:importtime,threadingoriginal=[3,1,15,2,9,6,3,2,7,1]result=[]pool=[]defsleepSort(num):time.sleep(num)result.append(num)fornuminoriginal:t=threading.Timer(num,sleepSort,args=(num,))pool.append(t)fortinpool:t.start()fortinpool:t.join()打印(结果)