简体   繁体   中英

Static Method Accessed by Multiple Threads With Pass By Reference

I have seen a lot of questions asked about static methods being accessed by multiple threads and the thread-safety of them. I think I have got most of it down in terms of ensuring thread safety, but one thing I am not too sure about is when you introduction the 'ref' variable into the mix within the static method itself. Here is a cut down example:

public static string ProcessMessage(object msg)
{

string outcome = "";

Decrypt(ref msg);

// parse msg

return outcome;

}

private static void Decrypt(ref object msg)
{

// decrypt msg

}

Is the above example thread-safe? All the processing that takes place within the static methods uses locally declared variables, it's just the ref object that gets passed from one static method to another that I'm unsure about.

It's not about static or not, it's about how the data operated by those methods is isolated.

If you operate on reference types , it's not thread-safe as is it presented in the code in both examples.

You need to you use some locking mechanism to ensure thread-safity.

It seems to me that it's thread-safe within itself but, of course, there is nothing stopping external factors doing odd stuff, like multiple threads calling in with the same reference. Some developers say this can be thread-unsafe. It could be if the common object contains thread-unsafe member data or methods that can reach such data, but this is taking your question a bit to extremes, to me.

Perhaps it's just me?

It would seem that almost every function/procedure I have written for the last 30 years is not thread-safe, especially the ones that work in multithreaded apps.

Your code looks like it doesn't need the ref parameter at all.

You can change it like this to ensure safety:

public static string ProcessMessage(object msg)
{

string outcome = "";

object decryptedMsg = Decrypt(msg);    

// parse decryptedMsg

return outcome;

}

private static object Decrypt(object msg)
{
object processedMsg;

// decrypt msg into processedMsg

return processedMsg;

}

since Decrypt is private, and msg is an object , I would assume this code to be safe while achieving the same result as your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM