Add threading support and some basic locking