【问题标题】:Why this code works and not crashing为什么此代码有效且不崩溃
【发布时间】:2016-02-13 07:31:22
【问题描述】:

我正在学习 C# 中的 volatile 、 interlock 和 lock ,在下面编写了代码以打印奇数和偶数而不使用任何这些同步结构,我多次运行此代码并且总是给出正确的答案,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace microsoft
{
    class th2_odd_event
    {
        static int num = 1;
        static bool guard = false;
        public void init()
        {
            Thread th = new Thread(print_odd);
            Thread th2 = new Thread(print_even);
            th.Start();
            th2.Start();

        }
        public static void print_odd()
        {
            while (true)
            {
                if (guard == false)
                {
                    if (num % 2 != 0)
                    {
                        Console.WriteLine(num);
                        num++;
                    }

                    guard = true;
                }
                if (num > 20)
                    break;
            }
        }

        public static void print_even()
        {
            while (true)
            {
                if (guard == true)
                {
                    if (num % 2 == 0)
                    {
                        Console.WriteLine(num);
                        num++;
                    }
                    guard = false;
                }

                if (num > 20)
                    break;
            }
        }

    }

这段代码是如何工作的?是运气好,两个线程之间没有冲突吗?我错过了一些东西......

【问题讨论】:

    标签: c# multithreading locking volatile interlocked


    【解决方案1】:

    还没有尝试过,但仅通过观察,如果您将 'guard' 变量视为锁定/互斥变量,这两个线程似乎只是在运行独占 while 循环。

    当奇数线程运行循环时,逻辑部分被命中,只有当'guard'为假时。此时,偶数线程将执行一个无操作的 while 循环,因为守卫不正确。 (如果检查是安全的,则为只读)

    最后,当奇数线程将保护设置为真时,它自己的 if 检查将返回假,而偶数线程的 if 检查将变为真并开始打印偶数。

    然后循环重复,线程几乎完全工作。 'guard' 变量仅在 if 块的末尾以原子分配方式更改,因此 2 个线程不会真正发生冲突。

    这就是您可能没有遇到任何问题的原因。

    【讨论】:

      猜你喜欢
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      • 2011-01-06
      • 2014-08-12
      • 1970-01-01
      • 2018-10-28
      相关资源
      最近更新 更多