dart-lang / sdk

The Dart SDK, including the VM, dart2js, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
9.95k stars 1.53k forks source link

`writeln` is not thread-safe #55345

Open ntkme opened 3 months ago

ntkme commented 3 months ago

https://github.com/dart-lang/sdk/commit/1d3d819ecfa2000ed11a137f5ee80df5bb687819 only partially fixed https://github.com/dart-lang/sdk/issues/53471, that the print function is now thread safe. However. stdout.writeln and stderr.writeln are still not thread safe.

stdout.writeln can be replaced with print in most cases, however, stderr.writeln does not have a thread-safe alternative.

import 'dart:isolate';
import 'dart:io';

void main() {
  Future.wait([
    for (var i = 0; i < 100; i += 1)
      Isolate.run(() {
        stdout.writeln('test');
      })
  ]);
}

@a-siva

lrhn commented 3 months ago

Must it be?

I'd personally accept any interleaving of the characters emitted by the isolates, as long as the ones from a single isolate are in the correct order. The Posix standard does require individual calls to be flock-ing on the FILE*, but we haven't promised that writeln is atomic, or that it's one Posix call.

If it's easy and cheap to fix, we should probably do it, just for the convenience. If not, maybe it just needs a disclaimer.

ntkme commented 3 months ago

We already made print behave this way. I guess it shouldn't be too hard to make writeln for at least stdout and stderr behave the same way.