PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] how to write decimal numbers as an atomic write in F#?

 August 10, 2022     decimal, f#, multithreading     No comments   

Issue

the decimal type takes 128 bits, so it is not naturally an atomic write.

I tried:

Interlocked.Exchange(ref myField, some new value)

but then I saw that decimal is not part of the supported types with Interlocked.Exchange.

I was thinking that doing a lock may be a little bit heavy for this write. Are there any other options?


Solution

As you said, Interlocked.Exchange can only work with 32bit or 64bit values, so it does not support decimal. Aside from using locks, one suggestion from a related C# StackOverflow post is to wrap the value in an object and then use Interlocked.Exchange to swap the object references. In F#, this would look like this:

type Boxed<'T when 'T : struct>(v:'T) = 
  member x.Value = v

let mutable d1 = Boxed(1M)
let d2 = Boxed(2M)

Interlocked.Exchange(&d1, d2)

The question is whether the overhead of an additional instance is greater than the overhead of using lock - I think this will depend on your specific case. If you have just a few decimals that you're working with, the extra objects may not be such a big deal, but you'll probably need to run some tests to find out.



Answered By - Tomas Petricek
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing