Published in


Ruby’s puts is not atomic

While improving a build script by parallelising actions, I realised that Ruby’s is not atomic.

Effects of the race condition in action

Looks like is calling the underlying function twice - Once to actually print the variable given to it, and once again to print the newline character. This leads to a race condition in , as observed above.

I confirmed this by taking a look at the source code for in Rubinius and MRI.

Annotated source code for puts in MRI, Rubinius

There is an open issue to fix this in MRI to fix this by using instead of https://bugs.ruby-lang.org/issues/9420

I worked around this by creating a function in our code, it looked like this:

By supplying ‘\n’ explicitly at the end, the whole string gets printed at once

This seems to be a problem with Python too, according to this StackOverflow post.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!



Elijah McClain, George Floyd, Eric Garner, Breonna Taylor, Ahmaud Arbery, Michael Brown, Oscar Grant, Atatiana Jefferson, Tamir Rice, Bettie Jones, Botham Jean

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Paul Kuruvilla

Practical and fact-minded individual, whose reliability cannot be doubted.