Questions tagged [interlocked]
Provides atomic operations for variables that are shared by multiple threads.
223
questions
0
votes
2
answers
129
views
Interlocked & Thread-Safe operations
1. Out of curiosity, what does operations like the following do behind the scenes when they get called for example from 2 or 3 threads at the same time?
Interlocked.Add(ref myInt, 24);
Interlocked....
3
votes
1
answer
93
views
Thread-safe lockless memory pool: free function does not behave correctly in multi-thread
I have a simple implementation of a thread-safe allocator of same-sized buffers.
Inside, the implementation is a very simple interlocked singly-linked list, that utilizes the unused space in ...
0
votes
0
answers
25
views
The code I wrote in the Mac's VS Code does not work in Windows's VS Code
without explanation from one's predecessor
I got the code as the zip file.
How can I run code written from the Mac on Windows as VS CODE?
enter image description here
0
votes
0
answers
35
views
Shared resource single thread writing, multiple thread reading using interlock
I'm trying to implement single thread writing, multiple thread reading mechanism for shared resource management using interlock in C++, windows environment.
Q1. The result code seems to work as what I ...
1
vote
2
answers
198
views
Proper way to synchronize a property's value in a multi-threaded application
I've recently started revisiting some of my old multi-threaded code and wondering if it's all safe and correct (No issues in production yet...). In particular am I handling object references ...
1
vote
0
answers
30
views
Does the Interlocked class work with FieldOffset?
I am trying to atomically assign two 32-bit values in C#. I have came up with a solution using FieldOffset on a struct and the 64-bit version of the Interlocked methods. I am wondering whether the ...
0
votes
1
answer
124
views
How to remove / reduce too many repetitive InterlockedCompareExchange?
I've learned that InterlockedCompareExchange() is used to read interlocked variables.
Also, InterlockedCompareExchange() is preferable rather than InterlockedOr() by Raymond Chen from the comments of ...
1
vote
1
answer
143
views
How to use interlocked variable for WaitOnAddress / WakeByAddressSingle?
Recently I've got to know WaitOnAddress, WakeByAddressSingle, and Interlocked* family of functions.
While making test code as a part of understanding process, I've faced C28112 warning.
Following code ...
0
votes
0
answers
57
views
warning C28112: A variable which is accessed via an Interlocked function must always be accessed via an Interlocked function
I'm getting this
"warning C28112: A variable which is accessed via an Interlocked function must always be accessed via an Interlocked function." when passing the address of shared variable, ...
0
votes
2
answers
130
views
Given an external producer API that can be stopped and started, efficiently stop the producer when local buffer is full
Suppose I am provided with an event producer API consisting of Start(), Pause(), and Resume() methods, and an ItemAvailable event. The producer itself is external code, and I have no control over its ...
0
votes
1
answer
83
views
Unique integer multiple threads
I am trying to generate unique integer Ids that can be used from multiple threads.
public partial class Form1 : Form
{
private static int sharedInteger;
...
private static int ...
0
votes
1
answer
211
views
C# Max counter with Interlocked [duplicate]
I've been given an assignment to write a max counter class with the following contract:
class MaxCounter
{
private int _value = int.MinValue;
public void Max(int value)
{
if(value > _value)
...
2
votes
1
answer
130
views
Is there any reason to prefer Interlocked over volatile for an Immutable Collection where updates do not depend on previous values?
I noticed that in questions discussing immutable collections (e.g. What is the preferred method of updating a reference to an immutable object?)
it was advised to use Interlocked (or better ...
1
vote
1
answer
82
views
Why declare a variable as volatile and use Interlocked on it at the same time? [duplicate]
I am reading Joe Duffy's Concurrent Programming on Windows. At the end of the chapter "Memory Models and Lock Freedom", he gives an example of the lock free stack. I have gone through the ...
1
vote
3
answers
443
views
Can Interlocked CompareExchange be used correctly in this multithreaded round-robin implementation?
I need to round-robin some calls between N different connections because of some rate limits in a multithreaded context. I've decided to implement this functionality using a list and a "counter,&...
2
votes
0
answers
159
views
Is there a way to perform an atomic (read-update-write) OR operation on two bytes in C#?
I looked at the Interlocked.Or method in .NET 5. This is great for two integer values. Is there a way to perform the equivalent of this on two separate byte values?
I searched the documentation, and I ...
0
votes
1
answer
159
views
Intelocked.Exchange instead of ReaderWriterLockSlim
In a multithreaded application, I have a Dictionary that is accessed by multiple threads for gettinng the value for a specific key. There is also a mechanism using Quartz.Net to update this dictionary....
1
vote
1
answer
128
views
Should InterlockedExchange be used on all setting of a variable?
I'm using InterlockedExchange in Windows and I have two questions that put together are basically my title question.
InterlockedExchange uses type LONG (32-bits). According to Microsoft's ...
4
votes
1
answer
12k
views
CS8625 Cannot convert null literal to non-nullable reference type warning for Interlocked.Exchange(ref c, null)
The following code works properly in .NET core 3.1, but generates wrongly the warning CS8625 Cannot convert null literal to non-nullable reference type:
#nullable enable
using System.Threading;
...
0
votes
0
answers
170
views
C# interlocked decrement on short value
I am doing some experimentation, and I need to atomically decrement a 16-bit (short) value in C#. The value is stored in unmanaged memory, and it is not a problem to ensure the value is aligned to a ...
1
vote
0
answers
87
views
Validity of InterlockedCompareExchange64 + Read32 operations mix
Objective:
I have a chunk of memory shared between several x86/x64 processes/threads.
Inside it I have QWORD (64 bit) variable aligned on 8-byte boundary.
That variable is accessed by one writer and ...
1
vote
1
answer
504
views
Why Interlocked.CompareExchange is not working?
if (Interlocked.CompareExchange(ref this.popcount, this.popcount + 1, this.popcount) == this.popcount)
{
pop = Interlocked.CompareExchange(ref head, head.next, head);
}
I write a code but somehow ...
0
votes
2
answers
979
views
Wait until a variable becomes zero
I'm writing a multithreaded program that can execute some tasks in separate threads.
Some operations require waiting for them at the end of execution of my program. I've written simple guard for such ...
0
votes
2
answers
60
views
How to turn on one of the toggle buttons
I want the other toggle button to turn off when one turns on.
<item android:state_checked="true"
android:drawable="@drawable/press"></item>
<item android:drawable="@drawable/nomal"&...
2
votes
0
answers
102
views
Is there some good reason for the return value of Interlocked.CompareExchange
The Interlocked.CompareExchange() method (docs) does roughly speaking this:
"I have a variable, and I think I know what value it currently has. If I'm right, then please change the value to that".
...
1
vote
2
answers
222
views
Interlocked.CompareExchange single-threaded equivalent code
I don't know why, but I can't quite seem to wrap my head around what's going on in Interlocked.CompareExchange(ref int a, int b, int c).
Could someone show me what it would be doing, if it were just ...
10
votes
2
answers
233
views
Should interlocked implementations based on CompareExchange use SpinWait?
Below is an implementation of an interlocked method based on Interlocked.CompareExchange.
Is it advisable for this code to use a SpinWait spin before reiterating?
public static bool AddIfLessThan(...
4
votes
1
answer
226
views
Difference between interlocked variable access (on boolean) and std::atomic_flag
I was wondering what the differences are between accessing a boolean value using Windows' interlockedXXX functions and using std::atomic_flag.
To my knowledge, both of them are lock-less and you can'...
5
votes
2
answers
334
views
What does "late-bound access to the destination object" mean?
The docs for Interlocked.Exchange<T> contain the following remark:
This method overload is preferable to the Exchange(Object, Object) method overload, because the latter requires late-bound ...
13
votes
2
answers
717
views
Difference between Threading.Volatile.Read(Int64) and Threading.Interlocked.Read(Int64)?
What is the difference, if any, of the Read(Int64) method of the .NET system classes System.Threading.Volatile and System.Threading.Interlocked?
Specifically, what are their respective guarantees / ...
2
votes
1
answer
76
views
Interlocked.CompareExchange instruction reodering of the initialvalue
Iam wondering if its possible that the initialvalue in the following code can be reordered to be after the computation resulting in undefined behavior.
The following example is taken from https://...
0
votes
1
answer
1k
views
Within Parallel.ForEach loop, I want to increment a var but Interlock.Increment doesn't seem to work
I've got a process that takes a long time so I want to break it out into Threads. My threading approach works fine with Parallel.ForEach, only I want to inform a user how many of the variable number ...
0
votes
0
answers
84
views
Listen on variable change in kernel thread with performance
This question is a continuation of a previously asked question:
Slow communication using shared memory between user mode and kernel
I am running a thread in the Windows kernel communicating with an ...
0
votes
1
answer
55
views
Is it possible to conditionally update a nullable long without locking?
I have long? startTime to hold start time.
I have multiple threads with non-async methods updating startTime and there's another async method in a separate thread that only ever read this value. The ...
2
votes
1
answer
394
views
improve atomic read from InterlockedCompareExchange()
Assuming architecture is ARM64 or x86-64.
I want to make sure if these two are equivalent:
a = _InterlockedCompareExchange64((__int64*)p, 0, 0);
MyBarrier(); a = *(volatile __int64*)p; MyBarrier();
...
3
votes
2
answers
118
views
Fastest way to safely read contents of long[] whose elements are changed concurrently
When you have a
long[] myArray = new long[256];
whose items are changed by multiple threads using
Interlocked.Increment(ref myArray[x])
it sure won't be possible to get a snapshot of myArray at ...
0
votes
1
answer
239
views
Interlocked.Exchange() with custom condition that relies in reading the locked variable
Original code:
var can = rateLock.WaitAsync();
if (can.IsCompletedSuccessfully) // for safety but do I need it?
{
if (!increase)
{
errorRate = (byte)(errorRate - Convert.ToByte(...
3
votes
0
answers
496
views
Interlocked Functions Don't Seem to Work as Expected in a Multithreaded PowerShell Script
I tried to utilize thread-safe DotNET classes (like BlockingCollection, ConcurrentQueue) and static functions (like Interlocked::Increment()) in my multithreaded PowerShell script (achieved through ...
1
vote
1
answer
57
views
Diverse output in parallel code
It prints correct result 4.5 with the same probability as 0.1, 0.2, 1, 2.3 and etc. What is wrong with it?
double average = 0;
Parallel.ForEach(
Enumerable.Range(0, 10),
() => 0,
(elem,...
0
votes
0
answers
82
views
_InterlockedCompareExchange64 does not work properly when is defined
Why the code below does not work correctly when _InterlockedCompareExchange64
is used as a define ? This instruction compares destination which is the 1st parameter with the 3rd parameter, and if they ...
0
votes
0
answers
97
views
Reading value before InterLocked.CompareExchange
I see following code in C# usage of InterLocked :
class MyObj {
// some class code ..
int myVal
public void foo()
{
int currVal = 0, newVal = 0;
do
{
currVal = this.myVal; // I ...
3
votes
1
answer
1k
views
C# - Interlocked Increment on a Dictionary Like List
I know that the int wont have a fixed position in memory so it simply cant work like that.
But The exact same portion of code will be run concurrently with different names, parameters e.t.c
I need to ...
2
votes
1
answer
187
views
How to update my model counter value using Interlocked.Add
So I have this model:
public class Container : INotifyPropertyChanged
{
private int _total;
private static InjectionContainer _mainContainer = new InjectionContainer();
private static ...
7
votes
2
answers
451
views
Interlocked.Exchange<T> slower than Interlocked.CompareExchange<T>?
I came across some odd performance results when optimizing a program, which are shown in the following BenchmarkDotNet benchmark:
string _s, _y = "yo";
[Benchmark]
public void Exchange() => ...
4
votes
0
answers
224
views
How are ref variables being captured in closure? [duplicate]
I have code like this (simplified):
long counter = 0L;
var t = Task.Run(async () =>
{
Interlocked.Increment(ref counter); // Resharper: "Access to modified closure"
await Task.Delay(500); ...
2
votes
0
answers
397
views
long vs {0L}[0]
In one of our old services I found such piece of code (comments are original):
long[] tasksCounter = {0}; //boxing for long counters
long[] errorsCounter = {0}; //boxing for long counters
Further ...
0
votes
1
answer
1k
views
Waiting on Interlocked == 0?
Disclaimer: My C# isn't even close to as good as my C++
I am trying to learn how to do async sockets in C# in order to write a test app for a component of mine. My former attempts using TcpClient ...
3
votes
1
answer
667
views
In MSVC, why do InterlockedOr and InterlockedAnd generate a loop instead of a simple locked instruction?
On MSVC for x64 (19.10.25019),
InterlockedOr(&g, 1)
generates this code sequence:
prefetchw BYTE PTR ?g@@3JC
mov eax, DWORD PTR ?g@@3JC ; g
npad 3
$LL3@...
3
votes
1
answer
169
views
Correct way of synchronization between a method and a stop functionality
I have a function (lets call it function A) that 0 to many threads can access it (at the same time, no shared resources). At any given time, the user can use to stop the process. The stop ...
1
vote
2
answers
527
views
How can I use an array item with Interlocked.CompareExchange
I'm familiar with using Interlocked.CompareExchange() with plain objects. However I'd like to use it with the member of an array:
string[] myArray = new string[] { "A", "B", "C" };
string myStr = (...