Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. a little further with System.Threading.Interlocked class

a little further with System.Threading.Interlocked class

Scheduled Pinned Locked Moved C#
csharptutorialquestionannouncement
1 Posts 1 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    mikewinny
    wrote on last edited by
    #1

    ok so perhaps not c# specific but its the language im using so... i have some (hopefully) thread-safe code that accesses some shared fields using the lock statement but im trying to avoid full-on locking. i need to update a field only if the result does not exceed some other value. i found the following code for simple value update (in the CompareExchange() example):

    do {
    initialValue = totalValue;
    computedValue = initialValue + addend;
    } while (initialValue != Interlocked.CompareExchange(ref totalValue, computedValue, initialValue));

    now, if i use the following would it be properly thread-safe and do wot i need..?

    do {
    initialValue = originalValue;
    result = initialValue + addValue;
    overFlag = result > maxValue;
    if (overFlag) result = initialValue;
    } while (initialValue != Interlocked.CompareExchange(ref originalValue, result, initialValue));

    overFlag is bool and would be used after the udpate code to determine whether to continue or not. i cant quite get my head around it. :confused: thanks in advance


    I worship his divine shadow.

    1 Reply Last reply
    0
    Reply
    • Reply as topic
    Log in to reply
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes


    • Login

    • Don't have an account? Register

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • World
    • Users
    • Groups