Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Runtime.InteropServices;
- using System.Threading;
- [StructLayout(LayoutKind.Sequential, Pack = 1)]
- struct Hello
- {
- byte padding1;
- public int value1;
- byte padding2;
- public int value2;
- }
- namespace Atomic
- {
- public class Program
- {
- public static void Main(string[] args)
- {
- Console.WriteLine("Offset {0}", Marshal.OffsetOf<Hello>("value1"));
- Console.WriteLine("Offset {0}", Marshal.OffsetOf<Hello>("value2"));
- var hello = new Hello();
- var t1 = new Thread(() => {
- while (true)
- {
- Thread.MemoryBarrier();
- hello.value1 = 0;
- hello.value2 = 0;
- }
- });
- t1.IsBackground = true;
- t1.Start();
- var t2 = new Thread(() => {
- while (true)
- {
- Thread.MemoryBarrier();
- hello.value1 = -1;
- hello.value2 = -1;
- }
- });
- t2.Start();
- t2.IsBackground = true;
- int error_count = 0;
- while (true)
- {
- Thread.MemoryBarrier();
- var v1 = hello.value1;
- var v2 = hello.value2;
- if ((v1 != 0 && v1 != -1) || (v2 != 0 && v2 != -1))
- {
- Console.WriteLine("{0} {1}", v1, v2);
- error_count++;
- if (error_count == 100)
- {
- break;
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement