dotnet / dotnet/csharpstandard

Specification issue: Atomicity (5.5)

Open
#273 2 comments 0 reactions 1 assignee Claimed by @MadsTorgersen View on GitHub
Dominant language
C#
Stars
815
Forks
99
Avg merge
1d 14h
Merged PRs (30d)
16

Description

C# Specification states, that "Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. ".
At the same time, CLI specification guarantee, that only **properly aligned** memory
locations no larger than the native word size (the size of type native int) is atomic (I.12.6.6). It means, that C# spec guarantee could be violated on structs with LayoutKind.Explicit.

**Version Used**: Visual Studio 201

**Steps to Reproduce**:

Compile sample bellow to x86 and run it:
```C#
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;

namespace ConsoleApplication1
{
[StructLayout(LayoutKind.Explicit)]
struct BadOffsetStruct
{
[FieldOffset(1)]
public uint Field ;
}

class Program
{
private static BadOffsetStruct strct = new BadOffsetStruct();
static void Main(string[] args)
{
strct.Field = 0xff;
var threads = new[]
{
new Thread(() => UpdateField(0xFF)),
new Thread(() => UpdateField(0xFF000000)),
};
foreach (var thread in threads)
{
thread.Start();
}
while (threads.Any(it=>it.IsAlive))
{
for (int i = 0; i < 1000000; i++)
{
var value = strct.Field;
if (value != 0xFF && value != 0xFF000000)
{
Console.WriteLine("{0:X}", value);
}
}
}
Console.WriteLine("Complete");
Console.ReadLine();
}

static void UpdateField(uint newValue)
{
DateTime start = DateTime.Now;
while (DateTime.Now - start < TimeSpan.FromSeconds(5))
{
for (int i = 0; i < 1000000; i++)
{
strct.Field = newValue;
}
}
}
}
}
```

**Expected Behavior**:
Only "Complete" outputs.
**Actual Behavior**:
Lots of stings 0, FF0000FF outputs before "Complete"

I believe that it is issue in C# specification. It should also point on **properly aligned** memory.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.