import _thread
import logging
from time import ctime,sleep
logging.basicConfig(level=logging.INFO)
def loop0():
logging.info("start loop0 at " + ctime())
sleep(4)
logging.info("ent loop0 at " + ctime())
def loop1():
logging.info("start loop1 at " + ctime())
sleep(2)
logging.info("end loop1 at " + ctime())
def main():
logging.info("start all at " + ctime())
# 同时进行
_thread.start_new_thread(loop0,())
_thread.start_new_thread(loop1,())
# 如果不延时6秒 main这个线程就结束了,会把thread里的进程kill掉
sleep(6)
logging.info("end all at " + ctime())
# 在当前模块
if __name__ == '__main__':
main()
import _thread
import logging
from time import ctime,sleep
logging.basicConfig(level=logging.INFO)
timer = [4,6]
def loop(index,nsec,lock):
print(nsec)
logging.info('start loop' + str(index) + ' at' + ctime())
sleep(nsec)
logging.info('end loop' + str(index) + ' at' + ctime())
lock.release()
def main():
logging.info('start all at ' + ctime())
locks = []
length = range(len(timer))
print(length)
for i in length:
lock = _thread.allocate_lock()
lock.acquire()
locks.append(lock)
for i in length:
_thread.start_new_thread(loop,(i,timer[i],locks[i]))
# 判断两个锁有被锁过 才执行下一行
for i in length:
while locks[i].locked():pass
logging.info('end all at ' + ctime())
if __name__ == '__main__':
main()
# #threading
import logging
import threading
from time import ctime,sleep
logging.basicConfig(level=logging.INFO)
timer = [4,6]
def loop(index,nsec):
logging.info('start loop' + str(index) + ' at' + ctime())
sleep(nsec)
logging.info('end loop' + str(index) + ' at' + ctime())
def main():
logging.info('start all at ' + ctime())
threads = []
length = range(len(timer))
for i in length:
t = threading.Thread(target=loop,args=(i,timer[i]))
threads.append(t)
for i in length:
threads[i].start()
for i in length:
threads[i].join()
logging.info('end all at ' + ctime())
if __name__ == '__main__':
main()
# #threading改写
import logging
import threading
from time import ctime,sleep
logging.basicConfig(level=logging.INFO)
timer = [4,6]
class MyThread(threading.Thread):
def __init__(self,fun,args,name=''):
threading.Thread.__init__(self)
self.fun = fun
self.args = args
self.name = name
def run(self):
print(self.name)
self.fun(*self.args)
def loop(index,nsec):
logging.info('start loop' + str(index) + ' at' + ctime())
sleep(nsec)
logging.info('end loop' + str(index) + ' at' + ctime())
def main():
logging.info('start all at ' + ctime())
threads = []
length = range(len(timer))
for i in length:
t = MyThread(loop, (i,timer[i]), loop.__name__+str(i))
threads.append(t)
for i in length:
threads[i].start()
for i in length:
threads[i].join()
logging.info('end all at ' + ctime())
if __name__ == '__main__':
main()