2

my question is simple: why some print dont get into next newline,

the following is my code:

def inner_func(lock):
    with lock:
        print (f'{threading.current_thread().getName()} - inner_function - lock1 - {time.time()}')
        print (f'{threading.current_thread().getName()} - inner_function - lock2 - {time.time()}')
        print (f'{threading.current_thread().getName()} - inner_function - lock3 - {time.time()}')
        time.sleep(1)
    print(f'{threading.current_thread().getName()} - inner_function - {time.time()}')

def outer_func(a, lock):
    inner_func(lock)
    print(f'{threading.current_thread().getName()} - outsider_function - input: {a} - {time.time()}')

class Worker():
    def __init__(self, num_threads, input_item):
        self.t             = threading
        self.lock          = self.t.Lock()
        self.q             = queue.Queue()
        self.num_thread    = num_threads
        self.input_item    = input_item

    def worker(self):
        while True:
            item = self.q.get()
            if item:    item.append(self.lock)
            if not item:
                break
            # outer_func(*item)
            outer_func(*item)
            self.q.task_done()

    def main(self):
        threads = []
        for _ in range(self.num_thread):
            t = self.t.Thread(target=self.worker)
            t.start()
            threads.append(t)

        for item in self.input_item:
            self.q.put(item)
        self.q.join()
        for _ in range(self.num_thread):
            self.q.put(None)
        for t in threads:
            t.join()

container = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g']]
Worker(7, container).main()

the following is some of my print output:

.....(some other print)
Thread-5 - inner_function - 1575727105.8761373Thread-7 - inner_function - lock1 - 1575727105.8761373
.....(some other print)

as you can see above, two different print merges into single line, how to prevent it. Thanks.

Kai
  • 77
  • 1
  • 13
  • Does this answer your question? [Python threading print overwriting itself](https://stackoverflow.com/questions/49130540/python-threading-print-overwriting-itself) – stovfl Dec 07 '19 at 15:05
  • Ok, I get it. Simple solution. Thank. – Kai Dec 08 '19 at 12:56

0 Answers0