Advertisement
Guest User

Untitled

a guest
May 8th, 2021
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.71 KB | None | 0 0
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Threading;
  4.  
  5. [StructLayout(LayoutKind.Sequential, Pack = 1)]
  6. struct Hello
  7. {
  8.     byte padding1;
  9.     public int value1;
  10.     byte padding2;
  11.     public int value2;
  12. }
  13.  
  14. namespace Atomic
  15. {
  16.     public class Program
  17.     {
  18.         public static void Main(string[] args)
  19.         {
  20.             Console.WriteLine("Offset {0}", Marshal.OffsetOf<Hello>("value1"));
  21.             Console.WriteLine("Offset {0}", Marshal.OffsetOf<Hello>("value2"));
  22.  
  23.             var hello = new Hello();
  24.  
  25.             var t1 = new Thread(() => {
  26.                 while (true)
  27.                 {
  28.                     Thread.MemoryBarrier();
  29.                     hello.value1 = 0;
  30.                     hello.value2 = 0;
  31.                 }
  32.             });
  33.             t1.IsBackground = true;
  34.             t1.Start();
  35.             var t2 = new Thread(() => {
  36.                 while (true)
  37.                 {
  38.                     Thread.MemoryBarrier();
  39.                     hello.value1 = -1;
  40.                     hello.value2 = -1;
  41.                 }
  42.             });
  43.             t2.Start();
  44.             t2.IsBackground = true;
  45.  
  46.             int error_count = 0;
  47.  
  48.             while (true)
  49.             {
  50.                 Thread.MemoryBarrier();
  51.                 var v1 = hello.value1;
  52.                 var v2 = hello.value2;
  53.  
  54.                 if ((v1 != 0 && v1 != -1) || (v2 != 0 && v2 != -1))
  55.                 {
  56.                     Console.WriteLine("{0} {1}", v1, v2);
  57.  
  58.                     error_count++;
  59.                     if (error_count == 100)
  60.                     {
  61.                         break;
  62.                     }
  63.                 }
  64.             }
  65.         }
  66.     }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement