10.3.1. Context switching in cooperative multitasking

This example demonstrates the use of the cooperative multitasking OS for defining concurrent tasks.

The printMsg() function is defined in file funclib.py in folder demo/parallel/cooperative/. It prints message msg n times. After every printout it allows a context switch to another task by calling cOS.Yield().

def printMsg(msg, n):
	# Prints a message n times, allows a context switch after every printed line
	# Context switch takes place at every OS system call. 
	for ii in range(n):
		print(msg+" : "+str(ii))
		cOS.Yield()
	return n

The following Python program spawns two concurrent tasks that print two messages. The first one prints it 10 times and the second oen 20 times. After the tasks are spawned the program waits for them to finish by using the cOS.Join() function.

File 01-context.py in folder demo/parallel/cooperative/

# Context switching

from pyopus.parallel.cooperative import cOS
from funclib import printMsg

if __name__=='__main__':
	# Spawn two tasks
	print("Spawning tasks")
	tidA=cOS.Spawn(printMsg, kwargs={'msg': 'Hello A', 'n': 10})
	tidB=cOS.Spawn(printMsg, kwargs={'msg': 'Hello B', 'n': 20})

	# IDs of running tasks
	running=set([tidA,tidB])
	print("Running tasks: "+str(running))

	# Wait for all tasks to finish
	while len(running)>0:
		# Wait for any task
		retval=cOS.Join()
		# Wait for tasks with specified IDs
		# retval=cOS.Join(running)
		
		# Remove IDs of finished tasks
		for tid in retval.keys():
			print("Task "+str(tid)+" finished, return value: "+str(retval[tid]))
			running.remove(tid)