SIMPLE threading tutorial

AutoPython 3 Tallied Votes 1K Views Share

!USING PYTHON 3.1!

Hello DaniWeb! Today I'm going to be posting a simple threading tutorial. First of all, what is threading? Well, threading is just another way of doing a side task without interrupting the main program. Now here's a simple example. Let's say we are going to make a simple program. When the program starts it is going to start a timer, and it will show the time. Now, observe these 2, similar programs.

Good version:

import threading
import time

threadBreak = False
def TimeProcess():
    while not threadBreak:
        print (time.time() - startTime)

startTime = time.time()

threading.Thread(target = TimeProcess).start()

input()
threadBreak = True
quit()

Bad Version:

import threading
import time

threadBreak = False
def TimeProcess():
    while not threadBreak:
        print (time.time() - startTime)

startTime = time.time()

TimeProcess()

input()
threadBreak = True 
quit()

Now, you may notice that, the working version will exit after you press any key. The not working version, will not let you quit after pressing anything. That is because this command:

threading.Thread(target = FunctionName)

Will run that function, but the function won't take control over the main code. Okay, now I have some more explaining to do. Let's view the commented version of the code:

import threading
import time

threadBreak = False
def TimeProcess():
    while not threadBreak: ## it will run this as long as threadBreak is false
        print (time.time() - startTime) 

startTime = time.time() ## I'm not sure how this works, just learned the trick.

threading.Thread(target = TimeProcess).start() ## Starts the thread in the background. 

input()
threadBreak = True ## stops the thread
quit()

That's a simple form of threading. But here's a more functional version of the above program.

import threading
import time

print ("Press any key to start timer!")
input()

threadBreak = False
def TimeProcess():
    while not threadBreak:
        print (time.time() - startTime)

startTime = time.time()

threading.Thread(target = TimeProcess).start()

input()
threadBreak = True
input ()
quit()

Well that's a simple threading tutorial! Threading can have many more uses, and don't only limit yourself to this.

lllllIllIlllI 178 Veteran Poster

Ah, excellent. threading is a great thing to show people.... Im still stuck for another idea for a tutorial though.. Unless i do wxPython ones. I already have some of those at my site tho :P

AutoPython 5 Junior Poster

Yeah, I just can't stand it seeing only 3 tutorials for such a great language. I want this place to be a significant source for tutorials.

soldner 0 Newbie Poster

Thanks for the threading, it is easier to understand when you see it. For more tutorials, how about the web? I'm using a php script in my wife's blog and would like to use Python.

What I don't know is:
How the php program is executed (how to execute the Python)
Where to variable mc_user_ip comes from, I think it is a return for the php program,
How do I see the return values,
How does the web pages's values get passed to the php program.

I've found some Python examples of getting the ip address, but the rest of it I haven't found.


<head>
<script src='http://code.vietwebguide.com/php/addr.php' type='text/javascript'></script>
<script type='text/javascript'>
//<!CDATA[
// Banned isps
var banned_ip = new Array();
banned_ip[0] = '72.129.151.108':
var mes_bi = "Kein Anschluss an diesen Nummer.";
for(var i=0;i<banned_ip.length;i++) {
eval('var re = /^' + banned_ip + '/ ;');
if (re.test(mc_user_ip))
{
document.write('<style type="text/css">');
document.write('BODY{display:none;}');
document.write('<\/style>');
alert(mes_bi);
break;
}
}
//]]>
</script>

AutoPython 5 Junior Poster

Hm, I am not familiar of using Python in the web. Try making a new thread on this and you'll probably get more help.

Leyond 0 Newbie Poster

Great tutorial, it is helpful..

albruno 0 Newbie Poster

for python
i believe that you need to execute it (if windows) through the cmd window
hope that this helps

Thanks for the threading, it is easier to understand when you see it. For more tutorials, how about the web? I'm using a php script in my wife's blog and would like to use Python.

What I don't know is:
How the php program is executed (how to execute the Python)
Where to variable mc_user_ip comes from, I think it is a return for the php program,
How do I see the return values,
How does the web pages's values get passed to the php program.

I've found some Python examples of getting the ip address, but the rest of it I haven't found.


<head>
<script src='http://code.vietwebguide.com/php/addr.php' type='text/javascript'></script>
<script type='text/javascript'>
//<!CDATA[
// Banned isps
var banned_ip = new Array();
banned_ip[0] = '72.129.151.108':
var mes_bi = "Kein Anschluss an diesen Nummer.";
for(var i=0;i<banned_ip.length;i++) {
eval('var re = /^' + banned_ip + '/ ;');
if (re.test(mc_user_ip))
{
document.write('<style type="text/css">');
document.write('BODY{display:none;}');
document.write('<\/style>');
alert(mes_bi);
break;
}
}
//]]>
</script>

marshrobin1 0 Newbie Poster

Excellent. Threading is a great thing to show people....thanks
Robin marsh:)

TrustyTony 888 pyMod Team Colleague Featured Poster

Here is little modified version to be more evident what it does:

## run with Python 3 from command line or double click
import threading
import time

def TimeProcess():
    while not threadBreak:
        print (time.time() - startTime)

input("""
Press enter key to start timer,
after some time push enter again to stop it!""")

threadBreak = False

startTime = time.time()

threading.Thread(target = TimeProcess).start()

input()
threadBreak = True
input ('Quit by enter')
quit()
woooee 814 Nearly a Posting Maven

Does everyone know about Doug Hellmann's Python Module Of The Week. A good source for basic learning.
http://www.doughellmann.com/PyMOTW/threading/index.html#module-threading
http://www.doughellmann.com/PyMOTW/about.html

TrustyTony commented: Nice examples of threading, subscribed RSS +2
_neo_ commented: Thanks, very useful tutorials are there +2
seanbp 4 Junior Poster
startTime = time.time() ## I'm not sure how this works, just learned the trick.

This line gets the current system time (a form which doesn't reset to zero). The script calculates the difference between the program start time and the current time.

twohot 0 Newbie Poster

That should fill the screen with a lot of time output .... shouldn't there be a sleep statement somewhere to make it more dramatic?

richieking 44 Master Poster

I am thinking of writting a tut about threading and socket. ;)

nytman 0 Light Poster

This thread is really nice, a good basics regarding thread, i was thinking to implement thread with some practicle use, so is there is any place where i could find threads with general examples where threads will do more than just printing time calculation .
Regards

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.