Concurrent Code Examples

2018/10/25

In today’s lecture, I put up three examples of code–one single-threaded version, one version that relies on separate processes, and one that relies on threads. This code is below.

Thread-based concurrency

import threading
import os
import time

def info(title):
    print(title)
    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())

def snoozer(snoozeNum, sleepTime):
    info('I am {}... about to sleep for {} seconds'.format(snoozeNum,sleepTime))
    time.sleep(sleepTime)
    print('Yawn... {} waking up now!'.format(snoozeNum))

if __name__ == '__main__':
    info('Main starting')
    input("Press any key to begin")

    threads = []
    for i in range(0,4):
        t = threading.Thread(target=snoozer, args=(i, 10*(i+1),))
        t.start()
        threads.append(t)
	
	for t in threads:
		t.join()

Process-based concurrency

from multiprocessing import Process
import os
import time

def info(title):
    print(title)
    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())

def snoozer(snoozeNum, sleepTime):
    info('I am {}... about to sleep for {} seconds'.format(snoozeNum,sleepTime))
    time.sleep(sleepTime)
    print('Yawn... {} waking up now!'.format(snoozeNum))

if __name__ == '__main__':
    info('Main starting')
    input("Press any key to begin")

    procs = []
    for i in range(0,4):
        p = Process(target=snoozer, args=(i, 10*(i+1),))
        p.start()
        procs.append(p)

    for p in procs:
        p.join()