First Steps into Concurrency

Great! A recent small assignment gave me a chance to truly dive into meaningful concurrent programming.

Demo

So, I created a small demo using Python’s queue, signal, and time modules. It’s not truly multithreaded, but serves as an illustrative example:

# -*- coding: utf-8 -*-
# @Author: Michale
# @Date:   2017-05-04 15:00:41
# @Last Modified by:   Michale
# @Last Modified time: 2017-05-07 00:46:52
import signal
import queue
import time


class TestClass(object):
    queue = queue.Queue()

    def __init__(self):
        signal.signal(signal.SIGINT, self.stopIfPressKill)

    def stopIfPressKill(self, mySignal, stack):
        if mySignal == signal.SIGINT:
            print('you pressed CTRL-C')
            self.queue.put_nowait('stop')
            print(self.queue.qsize())

    def mainThread(self):
        while True:
            time.sleep(1)
            if not self.queue.empty():
                data = self.queue.get()
                print(data)
                if data == 'stop':
                    break
                else:
                    self.queue.put(data)


if __name__ == '__main__':
    yoo = TestClass()
    yoo.mainThread()

Let me explain the roles of the three modules:

  • queue: Acts as a message queue, which is admittedly a bit overkill for this simple case.
  • signal: Used to capture KeyboardInterrupt and place a stop signal into the message queue.
  • time: Allows the main thread to have a chance to catch this KeyboardInterrupt.

Concept

The introduction of multithreading makes it difficult to control non-main threads once they are started, which forces the use of mechanisms like message queues for inter-thread communication.

However, whether multithreaded or not, system modules should encapsulate their internal details and collaborate through events. This greatly helps in reducing system coupling and is a key design philosophy for a good system: Design for change.

/python/ /concurrency/