0

I have been trying to use threading for multiple instances.

here is my code:

from threading import Thread
from random import randint
import time 


class MyThread(Thread):

    def __init__(self):
        Thread.__init__(self)

    def run(self):
        for x in range(1,5):

            print(self.getName())
            time.sleep(2)

       mythread1 = MyThread()
       mythread2 = MyThread()

       mythread1.setName('Thread 1')
       mythread2.setName('Thread 2')

When I start a thread. The output appears as expected.

 mythread2.start()

Output: Thread 2

But if I run the second thread in a different cell. The output of earlier cell appears in the different cell.

mythread1.start()

Output: Thread 1 Thread 2 Thread 1 Thread 2 Thread 1 Thread 2 Thread 1

I want the output to appear in each of its cell. I think the multi-threading is happening but the output appears in the last cell.

Is there something wrong in my process? I need to get each cell to print its own output.

Thanks!

enter image description here

SPYBUG96
  • 1,089
  • 5
  • 20
  • 38
Jitesh
  • 11
  • 1
  • 4
  • 1
    The nature of multithreading means that the output won't be confined to one cell, which is good - it means your multithreading is working as intended! Multithreading is asynchronous so different process will run relatively unpredictably like you're seeing. – 101 Nov 02 '18 at 13:37
  • I don't think there is a straightforward solution since when each thread calls "print" they write to "sys.stdout". You could for example change "stdout" for different threads so that they write in different cells independently, but this may be too complicated. I also recommend you check this out (https://stackoverflow.com/questions/14393989/per-cell-output-for-threaded-ipython-notebooks) – Trantidon Nov 02 '18 at 13:39

0 Answers0