I want to make a simple framework of a multi-threaded application that displays a string and falls asleep at the right time. Here is an example code:
import threading import thread from threading import Lock import sys from random import randint import time my_lock = Lock() class printer(threading.Thread): def __init__(self, string): threading.Thread.__init__(self) self.string = string #with my_lock: # print string def run(self): sys.stdout.write(self.string + '\n') sleep_time = randint(1, 10) time.sleep(sleep_time) max_threads = 5 f = open("strings.txt", "r") data = f.readlines() data_count = len(data) print data_count threads = [] i = 0 flag = True curr_threads = 0 while(flag == True): if(i >= data_count): flag = False if(flag != False): curr_threads = len(threads) while(curr_threads < max_threads): print i data_string = data[i] t = printer(data_string) threads.append(t) t.daemon = True t.start() i = i + 1 if ( i >= data_count): break for thr in threads: t_id = str(thr.ident) print "checking " + t_id if thr.is_alive(): t.join() print "handling" threads.remove(t) - First, for some reason, the main thread falls asleep
- secondly, I don’t know how to properly handle running threads
I thought it was necessary to go through all the working isAlive and if they isAlive then join and remove it from the list and so on. But join blocks the main program, so if a thread “sleeps” for a long time, then this is unproductive, and I cannot remove it from the list:
ValueError: list.remove (x): x not in list
How to correct the situation?