multithreading - python threading : cannot switch thread to Daemon -
i expect next code executed simultaneously , filenames os.walk iterations , got 0 @ random , in result dictionary. , threads have timeout deamon mode , killed script reaches end. however, script respects timeouts each thread.
why happening? should put threads in backgroung , kill them if not finish , return result before end of script execution? thank you.
import threading import os import time import random def check_file(file_name,timeout): time.sleep(timeout) print file_name result.append(file_name) result = [] home,dirs,files in os.walk("."): ifile in files : filename = '/'.join([home,ifile]) t = threading.thread(target=check_file(filename,random.randint(0,5))) t.setdaemon(true) t.start() print result solution: found mistake:
t = threading.thread(target=check_file(filename,random.randint(0,5))) has
t = threading.thread(target=check_file, args=(filename,random.randint(0,5))) in case, threading spawn thread function object ang give arguments. in initial example, function args has resolved before thread spawns. , fair.
however, example above works me @ 2.7.3 , @ 2.7.2 cannot make working. `m getting got exception
function check_file accepts 1 argument (34 given). soulution : in 2.7.2 had put ending coma in args tuple , considering have 1 variable . god knows why not affects 2.7.3 version .
t = threading.thread(target=check_file, args=(filename)) and started work
t = threading.thread(target=check_file, args=(filename,))
i understand trying do, you're not using right format threading. fixed example...look queue class on how properly.
secondly, never ever string manipulation on file paths. use os.path module; there's lot more adding separators between strings , don't think of time.
good luck!
import threading import os import time import random import queue def check_file(): while true: item = q.get() time.sleep(item[1]) print item q.task_done() q = queue.queue() result = [] home,dirs,files in os.walk("."): ifile in files: filename = os.path.join(home, ifile) q.put((filename, random.randint(0,5))) number_of_threads = 25 in range(number_of_threads): t = threading.thread(target=check_file) t.daemon = true t.start() q.join() print result
Comments
Post a Comment