Multithreading defined as the ability of a processor to execute multiple threads by rapidly switching the control of the CPU between threads concurrently.
import _thread
import time
# Define a function for the thread.
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print("%s: %s" %(threadName, time.ctime(time.time())))
# Create two threads as follows.
try:
_thread.start_new_thread( print_time,("Thread-1", 2,))
_thread.start_new_thread( print_time,("Thread-2", 4,))
except:
print("Error: unable to start thread")
while 1:
pass
import threading
def worker(num):
#thread worker function
print("Worker: %s", num)
return
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
import threading
import time
def worker():
print(threading.currentThread().getName(), "Starting")
time.sleep(2)
print(threading.currentThread().getName(), "Exiting")
def my_service():
print(threading.currentThread().getName(), "Starting")
time.sleep(3)
print(threading.currentThread().getName(), "Exiting")
t = threading.Thread(name='my_service', target=my_service)
w = threading.Thread(name='worker', target=worker)
w2 = threading.Thread(target=worker) # use default name
w.start()
w2.start()
t.start()
import threading
TOTAL = 0
class CountThread(threading.Thread):
def run(self):
global TOTAL
for i in range(100):
TOTAL = TOTAL + 1
print(TOTAL)
a = CountThread()
b = CountThread()
a.start()
b.start()