0

I am trying to gulp threading, and started with Python Module of the week examples:

according to below code

import threading

def worker(arg=None):
    """thread worker function"""
    print 'Worker thread: %s\n' % arg
    return

threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=str(i), name="threadingPrac")
    threads.append(t)
    t.start()

does this mean that I am starting 5 threads ?

I have just started with threading so want to understand it better.

2 Answers 2

1

Yes.

Add import time and time.sleep(5) after the print statement to better see it.

import threading
import time

def worker(arg=None):
    """thread worker function"""
    print 'Worker thread: %s\n' % arg
    time.sleep(5)
    return

threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=str(i), name="threadingPrac")
    threads.append(t)
    t.start()
Sign up to request clarification or add additional context in comments.

6 Comments

what I don't understand is these threads don't start simultaneously because for loop executes each thread one by one, so in what way threading will be helpful ? does that mean while the first thread is started and second is called at next iteration level then the second thread will executes parallely with the first thread and so forth ?
Maybe you should read some general texts about threads. You could start at en.wikipedia.org/wiki/Thread_(computing).
@san yes you are correct. Each subsequent threads will starts in each loop and do their operation. Python suffers from GIL, so you should consider using threads only in case of i/o bound tasks and not computational one. In case of computational tasks and want to achieve parallel processing, you should go for multiprocessing.
can you point me to an example that shows computational task and threading fails?
@san It's not that threading actually "fails", it's that because of the Global Interpreter Lock (GIL), most of the time only one thread can actually execute at a time, even if you have multiple CPU cores. So using threads for CPU-bound tasks will usually not be faster than using a single thread. It's even slower than a single thread sometimes, because of the extra overhead of switching between the threads over and over. When you want to parallelize CPU-bound tasks, use multiprocessing, which uses multiple processes instead of threads, and therefore isn't affected by the GIL.
|
0

Yes you can check the length of the list threads by adding this line at the bottom of your code:

print len(threads)

Output:

5 #Number of threads

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.