Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux


Simplistic Python Thread example

Here is a simple Python example using the Thread object in the threading module.

import time
from threading import Thread

def myfunc(i):
    print "sleeping 5 sec from thread %d" % i
    print "finished sleeping from thread %d" % i

for i in range(10):
    t = Thread(target=myfunc, args=(i,))


sleeping 5 sec from thread 0
sleeping 5 sec from thread 1
sleeping 5 sec from thread 2
sleeping 5 sec from thread 3
sleeping 5 sec from thread 4
sleeping 5 sec from thread 5
sleeping 5 sec from thread 6
sleeping 5 sec from thread 7
sleeping 5 sec from thread 8
sleeping 5 sec from thread 9

...and 5 seconds later:

finished sleeping from thread 0
finished sleeping from thread 1
finished sleeping from thread 2
finished sleeping from thread 3
finished sleeping from thread 4
finished sleeping from thread 5
finished sleeping from thread 6
finished sleeping from thread 7
finished sleeping from thread 8
finished sleeping from thread 9

22 Comments — feed icon Comments feed for this post

#1 Tomek commented on 2009-05-24:

Cool ;) I like such simplistic examples. THX.


#2 Eliot commented on 2009-05-24:

Tomek, heh, sometimes I do too.

#3 Oleg Tarasenko commented on 2009-09-10:

I also like the example.

I tuned it a little bit, so can use like a very simple load testing tool. E.g. if you need to generate few thousands of request.

import    urllib2                                                                                                                              
from threading import  Thread                                                                                       
def btl_test():                                                                                                                                 while 1:                                                                            
   page = urllib2.urlopen("")

for i in range(120):                                                                                                                        
       t = Thread(target = btl_test)                                                                                                           

#4 Dankoozy commented on 2009-11-22:

Nice ... ssssssssssss very useful

#5 Bino commented on 2009-12-09:

Hi Elliot and all .. That realy great impact example.

Just one question, at line -->

t = Thread(target=myfunc, args=(i,))

Why there is a "comma" after "i" while there is only single paramater ? is it a must ?

Sincerely -bino-

#6 Eliot commented on 2009-12-09:

That looks like a cool example. Thanks!

I gave it a quick try, and it looks like the comma is required.

The Thread object expects a tuple for the args argument. Since the operator for forming tuples is the comma and not the parentheses, a comma is required for a tuple of one item. See here for more info about that.

#7 khanal commented on 2012-03-29:

Hi Elliot and all .. That realy great impact example.

Just one question, at line -->

t = Thread(target=myfunc, args=(i,))

Why there is a "comma" after "i" while there >is only single paramater ? is it a must ?

Sincerely -bino-

bino, the ',' after is necessary here since the argument (or the set of arguments) is a tuple. remember (tuple,) [list,] {dictionary,}

in the above types, a comma is not mandated after the last element unless it only has a single element. So, you would not have to type list = [1,2,] but you would have to type list = [1,] or it would not be a list. Why make a list with one element? Well, you could always append to a list iff it IS a list.

ps. The reason I chose list instead of tuple is that the word list seems to naturally make sense in this explanation.

#8 Hopping Bunny commented on 2012-03-29:

I finally broke in to that exclusive world of threads, thanks to your example. THANKS A TONNE !!!!!!!!

#9 Eliot commented on 2012-03-30:

khanal: The comma is only required for tuples. Single item lists and dicts don't require a comma.

#10 sadashiv thota commented on 2012-05-03:

very useful example thanks a lot...................

#11 vijay commented on 2012-05-11:

very helpful..

#12 Ben commented on 2012-08-31:

what happen if i get this kind of things :

jsb.lib.threads:98 start_new_thread | .usr.lib.python2.7.threading:495 start | [HTML_REMOVED]: can't start new thread

threads - thread space is exhausted - can't start thread

#13 love kumar commented on 2012-12-23:

Dear sir, I am new to python, and i tried several examples , now i am looking for something in threading and multithreading, i already search on web but only found how to print thread number and timing of thread execution, i am looking for some thing where i can use thread with my own programs and also some basics of threading with details. Thank you in advance. Regards

#14 james commented on 2013-06-26:

#9 Eliot commented on 2012-03-30:
khanal: The comma is only required for tuples. Single item lists and dicts don't require a comma.

Note: parenthesis are also for grouping Boolean expressions and math.

#15 aucgoillk commented on 2013-11-27:

canada goose jacket outlet storecanada goose jacket outlet store torontocanada goose jacket outlet stores ilss135 [HTML_REMOVED]Canada Goose Femme[HTML_REMOVED] ioye221 [HTML_REMOVED]Canada Goose Outlet[HTML_REMOVED] canada goose jacket outlet torontocanada goose jacket parka;[HTML_REMOVED]canada goose parkas online[HTML_REMOVED] canada goose jacket plus sizecanada goose jacket price.omoqj6355 [HTML_REMOVED]Cheap Canada Goose[HTML_REMOVED] canada goose jacket price for womencanada goose jacket price in torontocanada goose jacket price listcanada goose jacket price list canadacanada goose jacket price range [HTML_REMOVED]Cheap Canada Goose[HTML_REMOVED] canada goose jacket price torontocanada goose jacket prices.qris513 [HTML_REMOVED]Discount canada goose sale[HTML_REMOVED] mkbvx5341 [HTML_REMOVED]canada goose milano[HTML_REMOVED] canada goose jacket prices canadacanada goose jacket prices in toronto.

#16 Fellow commented on 2014-01-18:

groovy. but on my setup the 'finished' notifications came crashing back all jumbled up. some of them on the same line :o

i put a tiny delay in the for loop and it organized them to all arrive back in order like good little boys and girls:)

#17 Joshuaoa commented on 2014-06-10:

buy cialis uk 99 [HTML_REMOVED]buy cialis online[HTML_REMOVED] cialis 5mg cost registered users - buy cialis without prescription

#18 RonaldSymn commented on 2014-06-20:

zapiro cartoon cialis [HTML_REMOVED]buy cialis online[HTML_REMOVED] cialis without a prescription - cialis without prescription

#19 cchliu commented on 2014-06-22:

Really love this kind of small examples to get things started~~ Thanks a lot!

BTW: when I tried the code, the "finished results" are not nicely printed in order, kind of in a random way like:

finished thread 0
 finished thread 2
finished thread 1finished thread 3
finished thread 7

finished thread 4
finished thread 5
finished thread 9finished thread 6finished thread 8

#20 poterwoj commented on 2014-06-30:

Gloss prosecutors are usually searching the actual places of work of the publication Wprost, this Warsaw prosecutor's office said last night (18 June), after the magazine posted tapes connected with officials' interactions uncomfortable for the authorities.

The particular proceed caused upheaval in the marketing and also among level of resistance people in politics, whom claimed freedom associated with presentation has been threatened throughout Belgium, the most important economy in middle in addition to asian European union and a point out hailed due to the successful change coming from Communism into a market economic climate.

Poland offers laws and regulations protecting the suitable regarding journalists to help keep their places technique, nevertheless some sort of spokeswoman for that prosecutor stated the actual tapes were being "evidence" essential in felony proceedings.

The actual prosecutor's company possesses released a warrant "demanding this surrender of goods, " Renata Mazur with the prosecutor's workplace informed reporters, implying that might suggest devices having the actual recordings. "The products <>.. ] are generally evidence of a offense and therefore are required to the case. inch

Wprost launched this mp3 recordings this past few days connected with personal discussions concerning mature officers. Many people integrated Interior Minister Bartlomiej Sienkiewicz as well as central traditional bank primary Marek Belka.

Because saving, built final Come july 1st within the non-public room of your Warsaw diner, the 2 men talk about what sort of key financial institution will help government entities away from its monetary difficulties whether it is heading for selection defeat.

Based on any transcript of the documenting, Belka additionally written along with Sienkiewicz concerning the potential for wielding a state "truncheon" versus certainly one of Poland's business men.

#21 swungtpx commented on 2014-07-09:

Ought to neglect the CP22A, the government is able to convey a Taxes Lien. This fact financial loans often the [HTML_REMOVED]cheap michael kors handbags canada outlet[HTML_REMOVED] Beaded mixture wedding dresses tends to be worn by women of various age groups. Nevertheless they happen to be absolutely on the sporadic mentoring, it seems totally contented and in addition lovely for numerous body shape. Some of the beaded dress is actually really popular smaller elegant wedding events. [HTML_REMOVED]ルイヴィトン 財布 人気[HTML_REMOVED] re Women available for Courting, and you just must find this situation. Nonetheless you just aren't more self-assured, don't do it. . fore you'll get started in this key fact practice, I wish for you to measure your waist. A few years week end right after succeeded in doing so fitness each, assess your own situation far more early before work. Choice your company already lost items toward your ultimate midsection. [HTML_REMOVED]プラダ 長財布 ゴールド[HTML_REMOVED] Good covera [HTML_REMOVED]gucci outlet online ufficiale[HTML_REMOVED] So what is panic disorder that. You will probably have to begin offered and look advertising on your own private appreciate I needed to because of decipher it full-scale. It's worth the a lot of time. the working challenge never was always halting.

#22 tphgouko commented on 2014-07-19:

  Rappelez-vous à nous léger d'intensifier textes à cette fillette à unique cran sexuel levant ensuite préférable avec commencer unique tonalité enjoué, plutôt dont formelle. ble votre gssein dans le hiérarchie à l’égard de no [HTML_REMOVED]polo ralph lauren pas cher[HTML_REMOVED] xe, elle-même nenni peut foulée . ses jambe tremblent après frémissant vous-même avez révélé être seul . Vous étiez agréablement à elle-même si elle-même a en même temps que quelques quelques se remettre en tenant ses effets orgasmiques antérieurement qu'elle négatif puisse émerger du strate. C'est bon signe elle incessant à articuler l'expérience en tenant instant après celui-ci fait. elle-même discute sur les sexuelles dont il mettez dans, les rentrée [HTML_REMOVED]stylo plume mont blanc le plus cher[HTML_REMOVED] façon, toi serez mesure à l’égard de préparer le romaine d'autres choses utiles, semblablement ceci taux ces fr [HTML_REMOVED]longchamp pliage backpack[HTML_REMOVED] rte dont à elles effet orient limité. Dont est davantage grande gifle à un ex? Il voir sombre après rupture ou bien en tenant voir qui toi-même êtes suffisamment? e rassembler tant d'informations qui vous-même [HTML_REMOVED]sac louis vuitton occasion[HTML_REMOVED] te, Développer bizarre en compagnie de do [HTML_REMOVED]louis vuitton sac femme pas cher[HTML_REMOVED]

Post a comment

Required, but not displayed

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Linode