Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threading and static methods in C#

Here is a meaningless extension method as an example:

public static class MyExtensions
{
    public static int MyExtensionMethod(this MyType e)
    {
        int x = 1;
        x = 2;

        return x
    }
}

Say a thread of execution completes upto and including the line:

x = 2; 

The processor then context switches and another thread enters the same method and completes the line:

int x = 1;

Am I correct in assuming that the variable "x" created and assigned by the first thread is on a separate stack to the variable "x" created and assigned by the second, meaning this method is re-entrant?

like image 374
Ben Aston Avatar asked Jun 27 '10 23:06

Ben Aston


People also ask

What is a static method in C?

A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.

Can we use static method in multithreading?

accessing the code is no problem, static methods can be called with multiple threads. It depends on how it is programmed in the method, if the code is not thread safe, it will cause problems.

Is static methods are thread safe?

A data type or static method is threadsafe if it behaves correctly when used from multiple threads, regardless of how those threads are executed, and without demanding additional coordination from the calling code.

Are there static methods in C?

Static functions in C are functions that are restricted to the same file in which they are defined. The functions in C are by default global. If we want to limit the scope of the function, we use the keyword static before the function.


1 Answers

Yes, each thread gets its own separate local variable. This function will always return 2 even if called by multiple threads simultaneously.

like image 196
Mark Byers Avatar answered Nov 02 '22 23:11

Mark Byers