Member Avatar for sravan953

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?

Recommended Answers

All 7 Replies

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 :)

Member Avatar for sravan953

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

Member Avatar for sravan953

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 :)

Member Avatar for sravan953

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()
Member Avatar for sravan953

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?

You really should read at least one tutorial on OOP and classes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.