Supernaturalo 2015-12-29 14:04 采纳率: 0%
浏览 2753

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

代码
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条回答 默认 最新

  • devmiao 2015-12-29 16:28
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退