0

I am beginning to learn how to create web applications from a golang tutorial. For simplicity, it persists data to files instead of a database. The complete code creates a server that can handle multiple simultaneous requests, but the program doesn't seem to ensure that only one user is interacting with a fixed file at a time.

Would this create problem for "real world" applications? Does an architecture which uses files for persistence create problems?

1 Answer 1

2

On Linux and POSIX systems, you'll better lock the file using e.g. advisory locking like flock(2) or lockf(3) (and if your application is multithreaded, you'll better use some way -e.g. mutexes- to ensure that only at most one single thread is accessing the file). You might have one (single and well defined) goroutine reading on some go channel for that synchronization.

This advisory locking ensures that other programs & processes following the same locking convention won't simultaneously access your file (but it won't forbid some program not using locking to access or write it).

If using a database, the DBMS is often guaranteeing ACID properties.

Some libraries (like sqlite, GDBM, ....) might have some way of locking files too.

You certainly should care about not having several threads or processes writing the same file simultaneously. This would be a race condition, and such bugs are difficult to reproduce and hard to find (read about heisenbugs).

2
  • Thank you for your thorough answers and informative links.
    – yberman
    Aug 10, 2015 at 13:45
  • In addition to a library which provides mutexs, the language has two builtin constructs for supporting parallelism: channels and coroutines (which I think are roughly analogous to synchronized queues and threads in other languages). Is there a natural way that express mutual exclusion using those tools?
    – yberman
    Aug 10, 2015 at 13:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.