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?

  • one
    you iterate over thr, and use t that was left from another cycle - etki
  • @Etki, yes, thank you, did not pay attention. But still, how to complete? If you do this: for thr in threads: thr.join () threads.remove (thr), then one hung thread will prevent you from generating a new one. - Alexander Pushkin
  • This is highly dependent on the task - you can wait through join, not wait at all, declare threads as demons and not care for them at all. If you need to continue working in the main thread, then just tell the threads to stop, and they will do it after a while. join is a forced formation of a state when a thread has already completed. - etki
  • @Etki, well, in general, I need the N thread to be started at the current time, so I did a cycle in which I complete the cleaned, and then add as much as necessary so that, as a result, N threads are currently running. - Alexander Pushkin
  • In this case, you do not need to wait for their completion, you just need to remove the dead and replace them with fresh ones - etki

0