synchronous call

  • Thread starter Thread starter Ivan
  • Start date Start date
I

Ivan

how to make a single method thread safe?

example:
class A
{
void func() {}
}

thread1:
A a1 = new A();
a.func();

thread2:
A a2 = new A();
a.func();


Ivan
 
Ivan,

The code that you just posted is actually thread safe because it doesn't
do anything.

Making an object or method call thread-safe depends on the granularity
you are looking to achieve, along with the resources you are trying to make
thread safe.

Can you be more specific about what you are trying to make thread-safe?
 
A.func() needs to be application-wide thread safe.
Having the example in mind, if a1 enters func(), a2 should wait.

example:
class A
{
void func() {}
}

thread1:
A a1 = new A();
a1.func();

thread2:
A a2 = new A();
a2.func();


Ivan
 
Ivan,

Check out the MethodImpl attribute, and pass in the
MethodImplOptions.Synchronized value to the attribute.

However, this will make any call on the object (you need to apply it to
every method) hold whenever any other method is called on any other thread.

Again, you didn't show anything that you were trying to synchronize, so
this is the most generic code you could use.
 
Again, you didn't show anything that you were trying to synchronize, so ...
synchronized code is substituted for simplicity by A.func()
this is code that only one thread needs to be in.
if I make it static and use this attribute (thanks for the attribute), my problem's fixed.

example:

using System.Runtime.CompilerServices;

class A
{
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public static void func() {}
}

thread1:
A a1 = new A();
a1.func();

thread2:
A a2 = new A();
a2.func();


Ivan
 
Back
Top