User:Laura Macchini/code/python threading

From XPUB & Lens-Based wiki

Simple Threading in Python

two while loops running at the same time ;)

import threading
import Queue
import time

val1 = 0
val2 = 0

def FirstLOOP(queue):
	global val1
	while True:
		val1 += 1
		queue.put("I am thread 1 and my value is: "+str(val1))
		time.sleep(1)

def SecondLOOP(queue):
	global val2
	while True:
		val2 += 1
		queue.put("I am thread 2 and my value is: "+str(val2))
		time.sleep(1)

def logger(queue):
	while True:
		print queue.get()


output_queue = Queue.Queue()

first  = threading.Thread(target=FirstLOOP, args=(output_queue,))
second = threading.Thread(target=SecondLOOP, args=(output_queue,))

first.start()
second.start()

logger(output_queue)