Is locking or Interlocked.Exchange required to swap a reference type field which is used in an other thread?












0















I know that there are .NET collections which are thread safe which I could use, but I still want to understand the following situation:



I have a Buffer class (below) which is used to writer data from a different thread, in a update loop interval (game) the main thread handles the data by swaping the list instance (to prevent both threads acting on the same instance at the same time).



So there is only a single additional thread who uses the "writerData" list, everything else is done on the main thread, but im not sure if the Swap method is thread "safe", because after searching for a while everyone seems to have a different opinion about swapping reference fields.



Some say that swapping reference doesn't require any locking other say that Interlocked.Exchange must be used in this case and other say it's not required, other say that the field must be violate and other say the keyword is "evil".



I know that threading is a difficult topic and maybe the other questions were too broad, but can someone help me to understand if any/which kind of "locking" is required in my specific case in the Swap method?



public class Buffer
{
List<byte> readerData;
List<byte> writerData; // This is the only field which is used by the other thread (by calling the Add method), well and by the Swap method, which is called from the main thread

// This method is only called by the other thread and it's the only method which is called from there
public void Add(byte data)
{
writerData.Add(data);
}
// Called on the main thread, before handling the readerData
public void Swap()
{
var tmp = readerData;
readerData = writerData
writerData = tmp;
}

// ... some other methods (which are only called from the main thread) to get the data from the (current) readerData field after calling the Swap method
}









share|improve this question























  • It depends on what the Main thread is thinking about readerData and writerData. Please consider that the Main thread is calling Swap() and at the same time, the other thread is adding data into the list. If the Main thread then thinks he has already processed everything in the reader List, he's wrong. So IMHO, the problem is not in the Swap() method, but potentially in the other methods you have not shown.

    – Thomas Weller
    Jan 1 at 16:57











  • Why don't you want to use Interlocked.Exchange()? You already know a solution that works. Why not use it? Sounds like the not-invented-here-syndrome. How sure are you that you'll never have more threads? One day it'll change and you're in trouble...

    – Thomas Weller
    Jan 1 at 17:00











  • Perhaps what you need is a ConcurrentQueue<byte>. That way you don't need two separate collections. You can write to it and read from it simultaneously.

    – Scott Hannen
    Jan 1 at 17:06











  • @ThomasWeller The first case you mentioned (adding data while Swap is called) would be "fine" in my case, because the data is handled in a update loop anways so it would still be handled in the next frame/interval which wouldn't be a problem in my use case. About Interlocked.Exchange() I don't have a problem with using it, but I want to understand/learn if I need it in this case or not

    – R1PFake
    Jan 1 at 17:17













  • The 'safety' of the Swap function depends on whether assigning references is atomic or not and the answer is: yes, it is safe. Meaning your code will never see an invalid (half written) reference.

    – Henk Holterman
    Jan 1 at 17:30


















0















I know that there are .NET collections which are thread safe which I could use, but I still want to understand the following situation:



I have a Buffer class (below) which is used to writer data from a different thread, in a update loop interval (game) the main thread handles the data by swaping the list instance (to prevent both threads acting on the same instance at the same time).



So there is only a single additional thread who uses the "writerData" list, everything else is done on the main thread, but im not sure if the Swap method is thread "safe", because after searching for a while everyone seems to have a different opinion about swapping reference fields.



Some say that swapping reference doesn't require any locking other say that Interlocked.Exchange must be used in this case and other say it's not required, other say that the field must be violate and other say the keyword is "evil".



I know that threading is a difficult topic and maybe the other questions were too broad, but can someone help me to understand if any/which kind of "locking" is required in my specific case in the Swap method?



public class Buffer
{
List<byte> readerData;
List<byte> writerData; // This is the only field which is used by the other thread (by calling the Add method), well and by the Swap method, which is called from the main thread

// This method is only called by the other thread and it's the only method which is called from there
public void Add(byte data)
{
writerData.Add(data);
}
// Called on the main thread, before handling the readerData
public void Swap()
{
var tmp = readerData;
readerData = writerData
writerData = tmp;
}

// ... some other methods (which are only called from the main thread) to get the data from the (current) readerData field after calling the Swap method
}









share|improve this question























  • It depends on what the Main thread is thinking about readerData and writerData. Please consider that the Main thread is calling Swap() and at the same time, the other thread is adding data into the list. If the Main thread then thinks he has already processed everything in the reader List, he's wrong. So IMHO, the problem is not in the Swap() method, but potentially in the other methods you have not shown.

    – Thomas Weller
    Jan 1 at 16:57











  • Why don't you want to use Interlocked.Exchange()? You already know a solution that works. Why not use it? Sounds like the not-invented-here-syndrome. How sure are you that you'll never have more threads? One day it'll change and you're in trouble...

    – Thomas Weller
    Jan 1 at 17:00











  • Perhaps what you need is a ConcurrentQueue<byte>. That way you don't need two separate collections. You can write to it and read from it simultaneously.

    – Scott Hannen
    Jan 1 at 17:06











  • @ThomasWeller The first case you mentioned (adding data while Swap is called) would be "fine" in my case, because the data is handled in a update loop anways so it would still be handled in the next frame/interval which wouldn't be a problem in my use case. About Interlocked.Exchange() I don't have a problem with using it, but I want to understand/learn if I need it in this case or not

    – R1PFake
    Jan 1 at 17:17













  • The 'safety' of the Swap function depends on whether assigning references is atomic or not and the answer is: yes, it is safe. Meaning your code will never see an invalid (half written) reference.

    – Henk Holterman
    Jan 1 at 17:30
















0












0








0








I know that there are .NET collections which are thread safe which I could use, but I still want to understand the following situation:



I have a Buffer class (below) which is used to writer data from a different thread, in a update loop interval (game) the main thread handles the data by swaping the list instance (to prevent both threads acting on the same instance at the same time).



So there is only a single additional thread who uses the "writerData" list, everything else is done on the main thread, but im not sure if the Swap method is thread "safe", because after searching for a while everyone seems to have a different opinion about swapping reference fields.



Some say that swapping reference doesn't require any locking other say that Interlocked.Exchange must be used in this case and other say it's not required, other say that the field must be violate and other say the keyword is "evil".



I know that threading is a difficult topic and maybe the other questions were too broad, but can someone help me to understand if any/which kind of "locking" is required in my specific case in the Swap method?



public class Buffer
{
List<byte> readerData;
List<byte> writerData; // This is the only field which is used by the other thread (by calling the Add method), well and by the Swap method, which is called from the main thread

// This method is only called by the other thread and it's the only method which is called from there
public void Add(byte data)
{
writerData.Add(data);
}
// Called on the main thread, before handling the readerData
public void Swap()
{
var tmp = readerData;
readerData = writerData
writerData = tmp;
}

// ... some other methods (which are only called from the main thread) to get the data from the (current) readerData field after calling the Swap method
}









share|improve this question














I know that there are .NET collections which are thread safe which I could use, but I still want to understand the following situation:



I have a Buffer class (below) which is used to writer data from a different thread, in a update loop interval (game) the main thread handles the data by swaping the list instance (to prevent both threads acting on the same instance at the same time).



So there is only a single additional thread who uses the "writerData" list, everything else is done on the main thread, but im not sure if the Swap method is thread "safe", because after searching for a while everyone seems to have a different opinion about swapping reference fields.



Some say that swapping reference doesn't require any locking other say that Interlocked.Exchange must be used in this case and other say it's not required, other say that the field must be violate and other say the keyword is "evil".



I know that threading is a difficult topic and maybe the other questions were too broad, but can someone help me to understand if any/which kind of "locking" is required in my specific case in the Swap method?



public class Buffer
{
List<byte> readerData;
List<byte> writerData; // This is the only field which is used by the other thread (by calling the Add method), well and by the Swap method, which is called from the main thread

// This method is only called by the other thread and it's the only method which is called from there
public void Add(byte data)
{
writerData.Add(data);
}
// Called on the main thread, before handling the readerData
public void Swap()
{
var tmp = readerData;
readerData = writerData
writerData = tmp;
}

// ... some other methods (which are only called from the main thread) to get the data from the (current) readerData field after calling the Swap method
}






c# multithreading thread-safety






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 1 at 16:49









R1PFakeR1PFake

1837




1837













  • It depends on what the Main thread is thinking about readerData and writerData. Please consider that the Main thread is calling Swap() and at the same time, the other thread is adding data into the list. If the Main thread then thinks he has already processed everything in the reader List, he's wrong. So IMHO, the problem is not in the Swap() method, but potentially in the other methods you have not shown.

    – Thomas Weller
    Jan 1 at 16:57











  • Why don't you want to use Interlocked.Exchange()? You already know a solution that works. Why not use it? Sounds like the not-invented-here-syndrome. How sure are you that you'll never have more threads? One day it'll change and you're in trouble...

    – Thomas Weller
    Jan 1 at 17:00











  • Perhaps what you need is a ConcurrentQueue<byte>. That way you don't need two separate collections. You can write to it and read from it simultaneously.

    – Scott Hannen
    Jan 1 at 17:06











  • @ThomasWeller The first case you mentioned (adding data while Swap is called) would be "fine" in my case, because the data is handled in a update loop anways so it would still be handled in the next frame/interval which wouldn't be a problem in my use case. About Interlocked.Exchange() I don't have a problem with using it, but I want to understand/learn if I need it in this case or not

    – R1PFake
    Jan 1 at 17:17













  • The 'safety' of the Swap function depends on whether assigning references is atomic or not and the answer is: yes, it is safe. Meaning your code will never see an invalid (half written) reference.

    – Henk Holterman
    Jan 1 at 17:30





















  • It depends on what the Main thread is thinking about readerData and writerData. Please consider that the Main thread is calling Swap() and at the same time, the other thread is adding data into the list. If the Main thread then thinks he has already processed everything in the reader List, he's wrong. So IMHO, the problem is not in the Swap() method, but potentially in the other methods you have not shown.

    – Thomas Weller
    Jan 1 at 16:57











  • Why don't you want to use Interlocked.Exchange()? You already know a solution that works. Why not use it? Sounds like the not-invented-here-syndrome. How sure are you that you'll never have more threads? One day it'll change and you're in trouble...

    – Thomas Weller
    Jan 1 at 17:00











  • Perhaps what you need is a ConcurrentQueue<byte>. That way you don't need two separate collections. You can write to it and read from it simultaneously.

    – Scott Hannen
    Jan 1 at 17:06











  • @ThomasWeller The first case you mentioned (adding data while Swap is called) would be "fine" in my case, because the data is handled in a update loop anways so it would still be handled in the next frame/interval which wouldn't be a problem in my use case. About Interlocked.Exchange() I don't have a problem with using it, but I want to understand/learn if I need it in this case or not

    – R1PFake
    Jan 1 at 17:17













  • The 'safety' of the Swap function depends on whether assigning references is atomic or not and the answer is: yes, it is safe. Meaning your code will never see an invalid (half written) reference.

    – Henk Holterman
    Jan 1 at 17:30



















It depends on what the Main thread is thinking about readerData and writerData. Please consider that the Main thread is calling Swap() and at the same time, the other thread is adding data into the list. If the Main thread then thinks he has already processed everything in the reader List, he's wrong. So IMHO, the problem is not in the Swap() method, but potentially in the other methods you have not shown.

– Thomas Weller
Jan 1 at 16:57





It depends on what the Main thread is thinking about readerData and writerData. Please consider that the Main thread is calling Swap() and at the same time, the other thread is adding data into the list. If the Main thread then thinks he has already processed everything in the reader List, he's wrong. So IMHO, the problem is not in the Swap() method, but potentially in the other methods you have not shown.

– Thomas Weller
Jan 1 at 16:57













Why don't you want to use Interlocked.Exchange()? You already know a solution that works. Why not use it? Sounds like the not-invented-here-syndrome. How sure are you that you'll never have more threads? One day it'll change and you're in trouble...

– Thomas Weller
Jan 1 at 17:00





Why don't you want to use Interlocked.Exchange()? You already know a solution that works. Why not use it? Sounds like the not-invented-here-syndrome. How sure are you that you'll never have more threads? One day it'll change and you're in trouble...

– Thomas Weller
Jan 1 at 17:00













Perhaps what you need is a ConcurrentQueue<byte>. That way you don't need two separate collections. You can write to it and read from it simultaneously.

– Scott Hannen
Jan 1 at 17:06





Perhaps what you need is a ConcurrentQueue<byte>. That way you don't need two separate collections. You can write to it and read from it simultaneously.

– Scott Hannen
Jan 1 at 17:06













@ThomasWeller The first case you mentioned (adding data while Swap is called) would be "fine" in my case, because the data is handled in a update loop anways so it would still be handled in the next frame/interval which wouldn't be a problem in my use case. About Interlocked.Exchange() I don't have a problem with using it, but I want to understand/learn if I need it in this case or not

– R1PFake
Jan 1 at 17:17







@ThomasWeller The first case you mentioned (adding data while Swap is called) would be "fine" in my case, because the data is handled in a update loop anways so it would still be handled in the next frame/interval which wouldn't be a problem in my use case. About Interlocked.Exchange() I don't have a problem with using it, but I want to understand/learn if I need it in this case or not

– R1PFake
Jan 1 at 17:17















The 'safety' of the Swap function depends on whether assigning references is atomic or not and the answer is: yes, it is safe. Meaning your code will never see an invalid (half written) reference.

– Henk Holterman
Jan 1 at 17:30







The 'safety' of the Swap function depends on whether assigning references is atomic or not and the answer is: yes, it is safe. Meaning your code will never see an invalid (half written) reference.

– Henk Holterman
Jan 1 at 17:30














0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53997229%2fis-locking-or-interlocked-exchange-required-to-swap-a-reference-type-field-which%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53997229%2fis-locking-or-interlocked-exchange-required-to-swap-a-reference-type-field-which%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

'app-layout' is not a known element: how to share Component with different Modules

android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

WPF add header to Image with URL pettitions [duplicate]