O'Reilly logo

Go Standard Library Cookbook by Radomir Sohlich

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How it works...

Writing concurrently to a file is a problem that can end up with inconsistent file content. It is better to synchronize the writing to the file by using Mutex or any other synchronization primitive. This way, you ensure that only one goroutine at a time will be able to write to the file. 

The preceding code creates a Writer with Mutex, which embeds the Writer (os.File, in this case), and for each Write call, internally locks the Mutex to provide exclusivity. After the write operation is complete, the Mutex primitive is unlocked naturally.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required