Supernaturalo
Supernaturalo
2015-12-29 14:04

nodejs使用co,yield多线程调用出现问题

  • node.js
  • 多线程

代码
var express = require('express');
var co = require("co");
var router = express.Router();
var mongoBasedao = require('../dao/mongoBasedao');
var connectionName = "test";
var c1 = 0;
var c2 = 0;

router.post('/', function (req, res) {
test(req, res);
});

function test(req, res) {
co(function*() {
var result = yield mongoBasedao.count({}, connectionName);
console.log("count:" + result);
c1++;
console.log("c1:" + c1);
if (result > 10) {
var error = {
code: 10000,
msg: "max"
}
return yield Promise.reject(error);
}
var doc = {
"name": "wade",
"age": 15
};
yield mongoBasedao.insertOne(doc, connectionName);
c2++;
console.log("c2:" + c2);
var success = {
code: 0,
msg: "success"
}
return yield Promise.resolve(success);
}).then(function (result) {
res.json(result);
}, function (err) {
res.json(err);
});
}

用20个线程同时访问接口
打印结果如下:
c1:1
c1:2
c1:3
c1:4
c1:5
c1:6
c1:7
c1:8
c1:9
c1:10
c1:11
c1:12
c1:13
c1:14
c1:15
c1:16
c1:17
c1:18
c1:19
c1:20
c2:1
POST /test 200 472.196 ms - 26
c2:2
POST /test 200 172.747 ms - 26
c2:3
POST /test 200 170.743 ms - 26
c2:4
POST /test 200 170.503 ms - 26
c2:5
POST /test 200 174.534 ms - 26
c2:6
POST /test 200 171.628 ms - 26
c2:7
POST /test 200 173.442 ms - 26
c2:8
POST /test 200 172.652 ms - 26
c2:9
POST /test 200 173.263 ms - 26
c2:10
POST /test 200 169.502 ms - 26
c2:11
POST /test 200 171.763 ms - 26
c2:12
POST /test 200 178.748 ms - 26
c2:13
POST /test 200 178.974 ms - 26
c2:14
POST /test 200 176.588 ms - 26
c2:15
POST /test 200 174.458 ms - 26
c2:16
POST /test 200 181.835 ms - 26
c2:17
POST /test 200 181.779 ms - 26
c2:18
POST /test 200 183.717 ms - 26
c2:19
POST /test 200 184.358 ms - 26
c2:20
POST /test 200 184.225 ms - 26

我以为打印结果 应该为 c1 c2 c1 c2 c1 c2 c1 c2 可是结果却是 c1 ... c2...
这个是什么原因 怎么解决这个问题啊

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答