1

Fibers and assignment operators work weirdly! It appears that using the += operator with a function doing a pause causes a bug. In this example, I launch 10 tasks in parallel, each one adds one to the sum. When work is done, the sum should be equal to 10 but I get 1.

Even weirder: if I replace sum += getOne(); by var one = getOne(); sum += one;, it works!

    "use strict";

    var Fiber = require("fibers");

    // returns 1 after a pause of 100ms
    var getOne = function() {
        var fiber = Fiber.current;

        // sleep 100ms
        setTimeout(function() {
            fiber.run();
        }, 100);
        Fiber.yield();

        return 1;
    };

    var bug = true; // change to test

    var sum = 0;
    var done = 0;

    var n = 10;
    var i;
    for (i=0; i<n; i++) {
        Fiber(function() {
            if (bug) {
                // bug!
                sum += getOne();
            }
            else {
                // no bug
                var one = getOne();
                sum += one;
            }

            if (++done === n) {
                console.log("sum = " + sum);
            }
        }).run();
    }
user3515941
  • 141
  • 1
  • 8

0 Answers0