!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.