Basic Multithreading Tutorial
For this tutorial we will be using Python 2.7.3
Hello python section, I am back with another tutorial. Today, we are going to learn some basic multithreading.
What is multithreading?
Multithreading is more or less having two parts of your program execute at the same time, while still sharing the same data. For example, you could have two while loops going at the same time.
Now, on to programming. First we will need to import the module for threading. Be sure to include time, we will be using it later.
Code
import threading, timeNow, we are going to have to have a function for the thread to use. Later on we can also build classes to use, but lets just do this for now. Lets make our function like this:
Code
import threading, time
def workerFunc(id):
while True:
time.sleep(0.5)
print "Hello from worker", str(id)This is just a simple function, that will wait half of a second and then print the phrase Hello from worker (id). Now we will set up the threading like this:
Code
import threading, time
def workerFunc(id):
while True:
time.sleep(1)
print "Hello from worker", str(id)
thread01 = threading.Thread(target=workerFunc, args=(1,))
thread02 = threading.Thread(target=workerFunc, args=(2,))
thread01.start()
time.sleep(3.7)
thread02.start()Now, when you run that you should get output something like this:
[img]http://img692.imageshack.us/img692/7752/14c20dc026114f9e8ea85ce.png[/img]
What this does so far, is makes two threads which use the function workerFunc. The id argument is passed to them. Then, the program starts thread01 and then waits 3.7 seconds, and then starts thread02.
Thats the end of this tutorial! Part 2 coming soon with object orientation and more advanced design.
![[Image: xyaO7.png]](https://i.imgur.com/xyaO7.png)

