Add lock to avoid short writes

When writing from multiple goroutines you might end up with short writes
and this lock will prevent it.

Perhaps this is not the most optimal solution but it's the easy one for
now.