locking Issue - Multiple Threads makes LOOP out of sequence - c#

I have a sample application and wonder if anyone can shine a light on this. When I put a breakpoint on the for loop an step into to the code in the debugger, why does it switch from one thread to another? it does so when running the application at runtime...Please see code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TPLSample
{
class Program
{
static void Main(string[] args)
{
Management m = new Management();
Task a = new Task(() => m.Operation1());
a.Start();
Task b = new Task(() => m.Operation2());
b.Start();
Console.ReadLine();
}
}
public class Management
{
A a = null;
B b = null;
public void Operation1()
{
a = new A();
}
public void Operation2()
{
b = new B();
}
}
public class A
{ Client a = new Client();
public A()
{
while (true)
{
a.Test("Im AAAAA");
}
}
}
public class B
{
Client a = new Client();
public B()
{
while (true)
{
a.Test("Im BBBBB");
}
}
}
public class Client
{
Object ibj = new Object();
public void Test(string item)
{
lock (ibj)
{
for (int i = 0; i < 200000; i++)
{
Console.WriteLine(item);
}
}
}
}
}
The result for this is a mixture of As and Bs. Isnt the lock suppose to block the thread so that the result will end up in sequence? The same is happening in an application I am writing except that the WHILE loops run forever (each task needs to poll continuosly). Please note that I am starting two tasks because I dont want one WHILE loop to prevent the other from running if the WHILE loop is to run forever. How do I make them go in sequence to that function in CLIENT class?

This happens because if you trace your object creation tree carefully you will notice that each thread is using a different lock object, thus rendering your lock statement useless.
Your object creation happens like this:
new A() -> new Client() -> new Object()
/
new Management()
\
new B() -> new Client() -> new Object()
You are using the last two objects on the right as locks, and you can clearly see that they are different objects.
Try to make the lock static:
public class Client
{
static Object ibj = new Object();
...
or otherwise rethink your hierarchy to pass the same lock to both Tasks.

Each object must have access to the same object to make the lock work. You can do this by making the ibj object static, or passing it into the Client class.
public class Client
{
static Object ibj = new Object();
public void Test(string item)
{
lock (ibj)
{
for (int i = 0; i < 200000; i++)
{
Console.WriteLine(item);
}
}
}
}

Related

Understanding C# threading interview question

I was recently asked a thread safety question in a c# interview. I didn't get it quite right.
I'm am trying to understand it now.
Here's the question...
Given a basic Order class...
using System;
namespace OrderThreadTest
{
public class Order
{
public TimeSpan CancelTime;
public int Id;
}
}
Given a simple schedule class stub however I have implemented it to test at home...
using System;
using System.Threading;
namespace OrderThreadTest
{
public class Scheduler : IDisposable
{
private Timer _timer;
public IDisposable Schedule(Order order, Action action)
{
var current = DateTime.Now;
var timeToGo = order.CancelTime - current.TimeOfDay;
_timer = new Timer(x => { action(); }, null, timeToGo, Timeout.InfiniteTimeSpan);
return this;
}
public void Dispose()
{
}
}
}
How do you ensure that the Cancel method in the worker class is thread safe?
My answer is the commented out pieces
using System;
namespace OrderThreadTest
{
public class Answer
{
private readonly Scheduler _scheduler;
private object _myLock = new object();
private Order _order;
public Answer(Scheduler scheduler)
{
_scheduler = scheduler;
}
public void Cancel(Order order)
{
// lock (_myLock)
// {
// _order = order;
// var result =
_scheduler.Schedule(order, () =>
{
//if (order.Equals(_order))
//{
Console.WriteLine("Canceled: " + order.Id);
order = null;
//}
});
// }
}
}
}
My first question in understanding this is how can I cause an example of a second thread setting the passed in Order and changing a earlier timer?
For example cause a thread data clash.
I have tried like this but it always seems to run as expected...
using System;
namespace OrderThreadTest
{
internal class Program
{
private static void Main(string[] args)
{
var a1 = new Answer(new Scheduler());
var o = new Order
{Id = 1, CancelTime = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second + 5)};
a1.Cancel(o);
a1.Cancel(o);
Console.ReadLine();
}
}
}
How do I repro the problem that I am meant to solve here?

Singleton - task inside constructor fails to start/ does not start asynchronically

I have a bit of weird problem that is hard to explain. I have singleton class where in the constructor I have to run a task to initialize some components/resources.
I used 2 implementation of singleton from C# in Depth and in one case everything is working fine, in another case - not.
Code is available below with some comments.
The main problem that for some reason task is not started in one case, when I am using static field with initialier and static contructor (class Test2).
I made some other tests and looks like with the implementation 2 task does not start asynchronically, but starts synchronically after waiting time.
Implementation one. everything is working as expected
public sealed class Test1
{
private static Test1 instance = null;
private static readonly object padlock = new object();
private Test1()
{
using (AutoResetEvent startEvent = new AutoResetEvent(false))
{
new Task(() => TaskThread(startEvent)).Start();
if (!startEvent.WaitOne(1000))
{
throw new Exception("ERROR");
}
}
}
public int Result()
{
return 10;
}
private void TaskThread(AutoResetEvent startEvent)
{
//I am initializing some stuff here
startEvent.Set();
}
public static Test1 Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Test1();
}
return instance;
}
}
}
}
Implementation 2, task is never started, or started after waiting time of an event
public sealed class Test2
{
private static readonly Test2 instance = new Test2();
static Test2()
{
}
private Test2()
{
using (AutoResetEvent startEvent = new AutoResetEvent(false))
{
new Task(() => TaskThread(startEvent)).Start();
//here it fails to wait successfully and throws an
//exception. Time limit is not reached
if (!startEvent.WaitOne(1000))
{
throw new Exception("ERROR");
}
}
}
public int Result()
{
return 20;
}
private void TaskThread(AutoResetEvent startEvent)
{
//I am initializing some stuff here as well
//but in this implementation code is never reached
startEvent.Set();
}
public static Test2 Instance
{
get
{
return instance;
}
}
}
I am curious why is this happening and how to avoid this problems in future. Thanks a lot!
The root cause of such 'strange' behavior is pretty simple - CLR executes static constructor under a lock. That prevents created thread from entering TaskThread() method and setting startEvent to signaled state.
After you face with such a problem and puzzle for several hours why this is happening, you start to understand why many sources advise not to use doubtful constructs like static constructors, global variables, etc.

Threading in c# with locks

I think i'm missing some basics in here and unable to fig out the problem..
Output of below program is not as expected. Can some one help me understand the issue here please.
using System;
using System.Threading;
public class Program
{
private static readonly object _lock = new object();
public static void Main()
{
for (var i = 0; i < 10; i++)
{
//Console.WriteLine("Start "+i);
System.Threading.Thread thread = new System.Threading.Thread(() => ExecuteInBackground(i));
thread.IsBackground = true;
thread.Start();
}
}
private static void ExecuteInBackground(Object obj)
{
lock (_lock)
{
Console.WriteLine("A "+obj);
test.ttt(obj);
}
}
}
public static class test
{
public static void ttt(object obj)
{
Console.WriteLine("B "+ obj);
}
}
I'm expecting to see 0 To 9 in output.. But actual output is as follows..
A 1
B 1
A 1
B 1
A 3
B 3
A 4
B 4
A 5
B 5
A 6
B 6
A 7
B 7
A 8
B 8
A 9
B 9
A 10
B 10
Any help is greatly appreciated.
Please feel free to play around with code in https://dotnetfiddle.net/nYfbMU
Thanks,
Reddy.
Change this:
for (var i = 0; i < 10; i++)
{
//Console.WriteLine("Start "+i);
System.Threading.Thread thread = new System.Threading.Thread(() => ExecuteInBackground(i));
to this:
for (var i = 0; i < 10; i++)
{
var temp = i;
//Console.WriteLine("Start "+i);
System.Threading.Thread thread = new System.Threading.Thread(() => ExecuteInBackground(temp));
This is a closure issue. See Why is it bad to use an iteration variable in a lambda expression
The reason the original code doesn't work as you expected, and why the temp variable does, is because () => ExecuteInBackground(i) is like saying "at some point in the future, I want this new thread to call the ExecuteInBackground method, passing in whatever value i has when that call is made". Since the loop variable goes into scope at the start of the loop, and out of scope after the loop is finished, the value of i changes between the time you call Thread, and when ExecuteInBackground executes. By using a temp variable inside the loop, that goes out of scope with every iteration of the loop, each thread's call to ExecuteInBackground is essentially getting a different variable with an unchanging value with each call, and the next incrementing of i doesn't mess things up.
This worked for me..
using System;
using System.Threading;
public class Program
{
private static readonly object _lock = new object();
public static void Main()
{
for (var i = 0; i <= 10; i++)
{
fn(i);
}
Console.ReadLine();
}
private static void fn(int i)
{
System.Threading.Thread thread = new System.Threading.Thread(() => ExecuteInBackground(i));
thread.IsBackground = true;
thread.Start();
}
private static void ExecuteInBackground(Object obj)
{
lock (_lock)
{
Thread.Sleep(500);
Console.WriteLine("A "+obj);
test.ttt(obj);
}
}
}
public static class test
{
//private static readonly object _lock = new object();
public static void ttt(object obj)
{
//lock(_lock)
Console.WriteLine("B "+ obj);
}
}

Mutithreading with sequence

I have a main task that is spawning threads to do some work. When the work is completed it will write to the console.
My problem is that some of the threads that are created later will finish faster than those created earlier. However I need the writing to the console to be done in the same exact sequence as the thread was created.
So if a thread had completed its task, while some earlier threads had not, it has to wait till those earlier threads complete too.
public class DoRead
{
public DoRead()
{
}
private void StartReading()
{
int i = 1;
while (i < 10000)
{
Runner r = new Runner(i, "Work" + i.ToString());
r.StartThread();
i += 1;
}
}
}
internal class Runner : System.IDisposable
{
int _count;
string _work = "";
public Runner(int Count, string Work)
{
_count = Count;
_work = Work;
}
public void StartThread()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(runThreadInPool), this);
}
public static void runThreadInPool(object obj)
{
((Runner)obj).run();
}
public void run()
{
try
{
Random r = new Random();
int num = r.Next(1000, 2000);
DateTime end = DateTime.Now.AddMilliseconds(num);
while (end > DateTime.Now)
{
}
Console.WriteLine(_count.ToString() + " : Done!");
}
catch
{
}
finally
{
_work = null;
}
}
public void Dispose()
{
this._work = null;
}
}
There may be a simpler way to do this than I used, (I'm used to .Net 4.0).
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication5
{
class Program
{
public static readonly int numOfTasks = 100;
public static int numTasksLeft = numOfTasks;
public static readonly object TaskDecrementLock = new object();
static void Main(string[] args)
{
DoRead dr = new DoRead();
dr.StartReading();
int tmpNumTasks = numTasksLeft;
while ( tmpNumTasks > 0 )
{
Thread.Sleep(1000);
tmpNumTasks = numTasksLeft;
}
List<string> strings = new List<string>();
lock( DoRead.locker )
{
for (int i = 1; i <= Program.numOfTasks; i++)
{
strings.Add( DoRead.dicto[i] );
}
}
foreach (string s in strings)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
public class DoRead
{
public static readonly object locker = new object();
public static Dictionary<int, string> dicto = new Dictionary<int, string>();
public DoRead()
{
}
public void StartReading()
{
int i = 1;
while (i <= Program.numOfTasks )
{
Runner r = new Runner(i, "Work" + i.ToString());
r.StartThread();
i += 1;
}
}
}
internal class Runner : System.IDisposable
{
int _count;
string _work = "";
public Runner(int Count, string Work)
{
_count = Count;
_work = Work;
}
public void StartThread()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(runThreadInPool), this);
}
public static void runThreadInPool(object obj)
{
Runner theRunner = ((Runner)obj);
string theString = theRunner.run();
lock (DoRead.locker)
{
DoRead.dicto.Add( theRunner._count, theString);
}
lock (Program.TaskDecrementLock)
{
Program.numTasksLeft--;
}
}
public string run()
{
try
{
Random r = new Random();
int num = r.Next(1000, 2000);
Thread.Sleep(num);
string theString = _count.ToString() + " : Done!";
return theString;
}
catch
{
}
finally
{
_work = null;
}
return "";
}
public void Dispose()
{
this._work = null;
}
}
}
}
Basically, I store the string you want printed from each task into a dictionary where the index is the task#. (I use a lock to make accessing the dictionary safe).
Next, so that the main program waits until all the background threads are done, I used another locked access to a NumTasksLeft variable.
I added stuff into the callback for the Runner.
It is bad practice to use busy loops, so I changed it to a Thread.Sleep( num ) statement.
Just change numOfTasks to 10000 to match your example.
I pull the return strings out of the dictionary in order, and then print it to the screen.
I'm sure you could refactor this to move or otherwise deal with the global variables, but this works.
Also, you might have noticed I didn't use the lock in the command
tmpNumTasks = numTasksLeft;
That's threadsafe, since numTasksLeft is an int which is read atomically on 32-bit computers and higher.
I don't know much on C#, but the whole idea of multi-threading is that you have multiple thread executing independently and you can never know which one will finish earlier (and you shouldn't expect earlier thread to end earlier).
One workaround is, instead writing out the finish message in the processing thread, have the processing thread setup a flag somewhere (probably a list with no of elements = no of thread spawned), and have a separate thread print out the finish message base on the flags in that list, and report up to the position that previous flag is consecutively "finished".
Honestly I don't feel that reasonable for you to print finish message like this anyway. I think changing the design is way better to have such meaningless "feature".
Typically, such requirements are met with an incrementing sequence number, much as you have already done.
Usually, the output from the processing threads is fed through a filter object that contains a list, (or dictionary), of all out-of-order result objects, 'holding them back' until all results with a lower seqeuence-number have come in. Again, similar to what you have already done.
What is not necessary is any kind of sleep() loop. The work threads themselves can operate the filter object, (which would beed a lock), or the work threads can producer-consumer-queue the results to an 'output thread' that operates the out-of-order filter.
This scheme works fine with pooled work threads, ie. those without continual create/terminate/destroy overhead.

Getting list of currently active managed threads in .NET?

For a "log information for support" type of function I'd like to enumerate and dump active thread information.
I'm well aware of the fact that race conditions can make this information semi-inaccurate, but I'd like to try to get the best possible result, even if it isn't 100% accurate.
I looked at Process.Threads, but it returns ProcessThread objects, I'd like to have a collection of Thread objects, so that I can log their name, and whether they're background threads or not.
Is there such a collection available, even if it is just a snapshot of the active threads when I call it?
ie.
Thread[] activeThreads = ??
Note, to be clear, I am not asking about Process.Threads, this collection gives me a lot, but not all of what I want. I want to know how much time specific named threads in our application is currently using (which means I will have to look at connecting the two types of objects later, but the names is more important than the CPU time to begin with.)
If you're willing to replace your application's Thread creations with another wrapper class, said wrapper class can track the active and inactive Threads for you. Here's a minimal workable shell of such a wrapper:
namespace ThreadTracker
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
public class TrackedThread
{
private static readonly IList<Thread> threadList = new List<Thread>();
private readonly Thread thread;
private readonly ParameterizedThreadStart start1;
private readonly ThreadStart start2;
public TrackedThread(ParameterizedThreadStart start)
{
this.start1 = start;
this.thread = new Thread(this.StartThreadParameterized);
lock (threadList)
{
threadList.Add(this.thread);
}
}
public TrackedThread(ThreadStart start)
{
this.start2 = start;
this.thread = new Thread(this.StartThread);
lock (threadList)
{
threadList.Add(this.thread);
}
}
public TrackedThread(ParameterizedThreadStart start, int maxStackSize)
{
this.start1 = start;
this.thread = new Thread(this.StartThreadParameterized, maxStackSize);
lock (threadList)
{
threadList.Add(this.thread);
}
}
public TrackedThread(ThreadStart start, int maxStackSize)
{
this.start2 = start;
this.thread = new Thread(this.StartThread, maxStackSize);
lock (threadList)
{
threadList.Add(this.thread);
}
}
public static int Count
{
get
{
lock (threadList)
{
return threadList.Count;
}
}
}
public static IEnumerable<Thread> ThreadList
{
get
{
lock (threadList)
{
return new ReadOnlyCollection<Thread>(threadList);
}
}
}
// either: (a) expose the thread object itself via a property or,
// (b) expose the other Thread public methods you need to replicate.
// This example uses (a).
public Thread Thread
{
get
{
return this.thread;
}
}
private void StartThreadParameterized(object obj)
{
try
{
this.start1(obj);
}
finally
{
lock (threadList)
{
threadList.Remove(this.thread);
}
}
}
private void StartThread()
{
try
{
this.start2();
}
finally
{
lock (threadList)
{
threadList.Remove(this.thread);
}
}
}
}
}
and a quick test driver of it (note I do not iterate over the list of threads, merely get the count in the list):
namespace ThreadTracker
{
using System;
using System.Threading;
internal static class Program
{
private static void Main()
{
var thread1 = new TrackedThread(DoNothingForFiveSeconds);
var thread2 = new TrackedThread(DoNothingForTenSeconds);
var thread3 = new TrackedThread(DoNothingForSomeTime);
thread1.Thread.Start();
thread2.Thread.Start();
thread3.Thread.Start(15);
while (TrackedThread.Count > 0)
{
Console.WriteLine(TrackedThread.Count);
}
Console.ReadLine();
}
private static void DoNothingForFiveSeconds()
{
Thread.Sleep(5000);
}
private static void DoNothingForTenSeconds()
{
Thread.Sleep(10000);
}
private static void DoNothingForSomeTime(object seconds)
{
Thread.Sleep(1000 * (int)seconds);
}
}
}
Not sure if you can go such a route, but it will accomplish the goal if you're able to incorporate at an early stage of development.
Is it feasible for you to store thread information in a lookup as you create each thread in your application?
As each thread starts, you can get its ID using AppDomain.GetCurrentThreadId(). Later, you can use this to cross reference with the data returned from Process.Threads.

Categories

Resources