Just Code‎ > ‎

Static functions are thread safe if they do not modify any other variables than those they create themself

posted Aug 28, 2009, 7:16 AM by Peter Henell   [ updated Aug 30, 2009, 8:36 AM ]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(
delegate
{
ThreadTester.AddToValue(18, "First thread");
}));
Thread t2 = new Thread(new ThreadStart(
delegate
{
ThreadTester.AddToValue(44, "Second thread");
}));

t1.Start();
t2.Start();
}
}

class ThreadTester
{
public static int AddToValue(int value, string callingThread)
{
int a = 5;
int b = a + value;
a += 20;

while(a == 25)
{
Console.WriteLine(@"Waiting for other thread to change my values, i have
thread = {0}
a = {1}
b = {2}
value = {3}", callingThread, a, b, value);
b++;
System.Threading.Thread.Sleep(5000);
}

return a;
}
}
}