Example 1: threading python example
import threading
import time
def loop1_10():
for i in range(1, 11):
time.sleep(1)
print(i)
threading.Thread(target=loop1_10).start()
import threading
import time
class MyThread(threading.Thread):
def run(self):
print("{} started!".format(self.getName()))
time.sleep(1)
print("{} finished!".format(self.getName()))
def main():
for x in range(4):
mythread = MyThread(name = "Thread-{}".format(x))
mythread.start()
time.sleep(.9)
if __name__ == '__main__':
main()
Example 2: how to thread python
import threading, time
def worker():
"""thread worker function"""
print('Worker')
return
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.append(t)
t.start()
print('Thread')
Example 3: launch a script from python using threading
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
print_time(self.name, 5, self.counter)
print "Exiting " + self.name
def print_time(threadName, counter, delay):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
thread1.start()
thread2.start()
print "Exiting Main Thread"
Example 4: python threading
def myFunction(x, y):
pass
x = threading.Thread(target=myFunction, args=(x, y))
x.start()
Example 5: how to run same function on multiple threads in pyhton
import multiprocessing
def worker(num):
""" Worker procedure
"""
print('Worker:', str(num))
if __name__ == '__main__':
jobs = []
jobs_num = 5
for i in range(jobs_num):
p1 = multiprocessing.Process(target=worker, args=(i,))
jobs.append(p1)
p2 = multiprocessing.Process(target=worker, args=(i+10,))
jobs.append(p2)
p1.start()
p2.start()
Example 6: multithreading python
class FakeDatabase:
def __init__(self):
self.value = 0
self._lock = threading.Lock()
def locked_update(self, name):
logging.info("Thread %s: starting update", name)
logging.debug("Thread %s about to lock", name)
with self._lock:
logging.debug("Thread %s has lock", name)
local_copy = self.value
local_copy += 1
time.sleep(0.1)
self.value = local_copy
logging.debug("Thread %s about to release lock", name)
logging.debug("Thread %s after release", name)
logging.info("Thread %s: finishing update", name)