Using Threads in Twisted

Introduction

Before you start using threads, make sure you do at the start of your program:

from twisted.python import threadable
threadable.init(1)

This will make certain parts of Twisted thread-safe so you can use them safely. However, note that most parts of Twisted are not thread-safe.

Running code in a thread-safe manner

Most code in Twisted is not thread-safe. For example, writing data to a transport from a protocol is not thread-safe. Therefore, we want a way to schedule methods to be run in the main event loop. As discussed in the Scheduling document, this can be done using twisted.internet.task module.

from twisted.internet import task

def notThreadSafe(x):
     """do something that isn't thread-safe"""
     # ...

def threadSafeScheduler():
    """Run in thread-safe manner."""
    task.schedule(notThreadSafe, 3) # will run 'notThreadSafe(3)' in the event loop