多核处理器上的线程问题 [英] Threading issue on Processor with multiple core

查看:156
本文介绍了多核处理器上的线程问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码来使用多个线程更新变量

I have written following code to update a variable using multiple thread

namespace InterlockedApp
{
    class Program
    {
        static void Main(string[] args)
        {
            MyNum n = new MyNum();
            for (int i = 0; i < 10; i++)
            {
            for(int j=0;j<100;j++)
            {
                Thread t = new Thread(new ThreadStart(n.AddOne));
                t.Start();
            }
                Console.WriteLine(n.num);
            }
        }
    }
    public class MyNum
    {
        public int num = 1;
        public void AddOne()
        {
                Interlocked.Increment(ref num);

        }

    }
}



为了确保该值不会被覆盖,我正在使用互锁.基于输出应该是
100
200
300
..
.
.
1000

但是我得到的是
100
200
300
499
501
...

1001

每次运行程序时,输出都与理想情况不同.

知道代码有什么问题吗?



To make sure the value is not overwritten, I am using Interlocked. Based on the the out put should be
100
200
300
..
.
.
1000

But what I am getting is
100
200
300
499
501
...

1001

Everytime you run the program, output is different from ideal...

Any idea what is wrong with the code?

推荐答案

这是完美预期,甚至是理想的结果.

它不取决于您运行的内核数量,即使在单核单CPU计算机上也可以预期达到相同的效果.看来您在这种情况下不希望并行执行,为什么要使用线程呢?

如果您解释您的最终目标和关于您希望从并发执行中获得什么的想法,它可以获取进一步的建议.在现实生活中,大多数高级应用程序都需要并发方案.

—SA
This is perfectly expected and even desirable result.

It does not depend on how many cores you''re running, the same effect you can expect even on a single-core single-CPU computer. It looks like you don''t want parallel execution in this case, why using thread then?

If you explain your ultimate goal and the idea on what you want to get from concurrent execution, it can get further advice. In real life, most more or less advanced applications require concurrent scenarios.

—SA


如果您希望输出显示100、200,...,如您所解释的,那么您需要等待所有线程完成后才能打印输出,然后开始下一个,依此类推.

SA是对的:这意味着您在这种情况下根本不需要广告.

顺便说一句,您还应该将num初始化为 0 而不是 1 ...
If you want the output to display 100, 200, ... as you explained, then you need to wait for all threads to finish before printing the output, then start the next ones, and so on.

SA is right: it means you don''t need theads at all in your scenario.

By the way, you should also initialize num to 0 and not 1...


这篇关于多核处理器上的线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆