Hey guys,

I have already worked on a program which uses threads, but today I just wanted to work on threading, and only threading:

import threading

class first_time(threading.Thread):
    def print_first_time(self):
        print("What is your name?")

for x in range(1000):
               first_time().start()

But, the problem is, nothing happens! Why is it acting so strangely?

Threading is a bit more complex than that. First we need to start the __init__ method of the threading class soo

import threading

class first_time(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

There we go, threading class's constructor has run, now the new class has all the attributes from the Thread class.

Now when we go first_time.start() it actually runs a method called run, so lets add that to our code

import threading

class first_time(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        print("What is your name?")

Now when we do our final loop we it will run the method called run. But we also need to make an object of our class to use it.

so

import threading

class first_time(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        print("What is your name?")

#our class object
f = first_time()

for x in range(1000):
    f.start()

Hope that helps :)

What is threading.Thread.__init__(self) for(is it short for 'initialize'? Where else is __init__ used?

And also, can't I name the second function as something else?

Thanks

Oh and, I don't why paulthom12345 but your code doesn't work. It says thread has already been started!

Yeah, i thought that may have a possibility of happening. I didnt debug the code... woops :P

Anyway, ill get onto it tomorrow. i have a lot of sleeping to do in the meantime :)

I finally got it to work! ;)

All I had to do was, instead of:

f = first_time()

for x in range(1000):
    f.start()

-I did this:

for x in range(1000):
    first_time().start()

And can you please explain to me in detail what the __init__ is for? Also, why do we specify self in the threading.Thread.__init__(self) line?

Edited 3 Years Ago by pritaeas: fixed formatting

This article has been dead for over six months. Start a new discussion instead.