I am developing an app for windows phone 7.Now I have 2 threads.
thread 1
lock(somelock)
{
//does some work
Monitor.Wait();
//Does some work
}
thread 2
lock(somelock)
{
//does some work
Monitor.Signal();
//does some work;
}
Now I want to know whether Monitor.wait() signals the other thread.
A thread that fails to get a lock is held in the ready queue. If the thread with the lock calls Wait, then it yields the lock and any threads in the ready-queue are eligible to be activated, obtaining the lock. So in a way they are activated, but they aren't "pulsed", if that is what you mean by signalled.
By contrast, the thread that voluntarily called Wait is in a separate queue; it doesn't become activated just by a thread yielding the lock; the only way that thread gets back into the ready queue is if either a thread with the lock calls Pulse/PulseAll, or the timeout occurs. Note that Pulse/PulseAll do not yield the lock - they just more a thread/threads from the sleeping queue to the ready-queue. The lock in the second example is only yielded when leaving the lock statement. As a consequence of this, note that the "does some work" after the Pulse (Signal in your example) is still done while holding an exclusive lock (in effect, you might as well move the Pulse to the end of the lock statement).
No, but Monitor.Pulse() does. Use Monitor.Pulse() when you want to signal that the state may have changed for a Monitor.Wait() condition.
http://www.albahari.com/threading/part4.aspx#_Signaling_with_Wait_and_Pulse
Related
I have a part of code in an Async/Await function that I only want one thread to execute at a time.
This is relatively simple by creating a new SemaphoreSlim(1) and using WaitAsync/Release. The effect is that the first thread executes while the others wait and then execute one by one.
What I am trying to achieve is actually slightly different. I would like the other threads not to wait, but to return out of the function (i.e. I don't want to block the other threads). So if there was a property "NumberOfThreadsCurrentlyExecuting" I would effectively have an If Semaphore.NumberOfThreadsCurrentlyExecuting > 0 Then Return.
But such a property doesn't exist. Does anyone have any idea for a way around this problem?
Thanks
Charles
How about using the SemaphoreSlim.Wait/Async with a zero-timeout? If it can't enter the semaphore (because it's already been entered), it will return false.
Note that Monitor (and thus lock) is completely unsuited to async
(hence the fact that you can't await in a lock) because
your task may continue on another thread after you've entered the lock (thus you will try to release the lock from another thread)
after you've awaited, another continuation may use your thread (while it is still holding the lock), so if it attempts to acquire the lock it will succeed
Instead of a Semaphore, you could just use a Monitor.
If you call TryEnter and it fails, another thread is in the "lock".
This is thread safe (unlike checking semaphore counts), and fairly simple:
// using somethign like: object sync = new object();
bool lockTaken = Monitor.TryEnter(sync);
try
{
if (lockTaken)
{
// You're here - do your work
}
else
{
// Something else was in the thread - exit?
return;
}
}
finally
{
if (lockTaken) Monitor.Exit(sync);
}
under both aborted and completed situations, ThreadState will be Stopped.
How to differentiate between them?
Your original assertion is not correct. Consider:
public static void TestThreadAbort()
{
var t = new Thread(() => Thread.Sleep(50000));
t.Start();
t.Abort();
Thread.Sleep(50);
// Prints "Aborted"
Console.WriteLine(t.ThreadState);
}
Note how the ThreadState enum is declared:
[FlagsAttribute]
public enum ThreadState { ... }
...Sinc it is a [Flag] this means a thread can be in multiple states.
MSDN, ThreadState Enumeration (emphasis added by me):
ThreadState defines a set of all possible execution states for
threads. Once a thread is created, it is in at least one of the states
until it terminates. Threads created within the common language
runtime are initially in the Unstarted state, while external threads
that come into the runtime are already in the Running state. An
Unstarted thread is transitioned into the Running state by calling
Start. Not all combinations of ThreadState values are valid; for
example, a thread cannot be in both the Aborted and Unstarted states.
...and then goes on to say:
A thread can be in more than one state at a given time. For example,
if a thread is blocked on a call to Wait, and another thread calls
Abort on the blocked thread, the blocked thread will be in both the
WaitSleepJoin and the AbortRequested states at the same time. In this
case, as soon as the thread returns from the call to Wait or is
interrupted, it will receive the ThreadAbortException to begin
aborting.
The Thread.ThreadState property of a thread provides the current state
of a thread. Applications must use a bitmask to determine whether a
thread is running. Since the value for Running is zero (0), test
whether a thread is running by using C# code such as
(myThread.ThreadState & (ThreadState.Stopped | ThreadState.Unstarted)) == 0
When a thread is aborted . You get ThreadAbortException on your thread.
This can help you in differentiating.
The only way I can think of is to set a "completed" flag as the last action in your thread. If that flag isn't set, you can assume it was aborted. As #Chris Shain points out below, you have to be careful where you put it, though, since in the case of a thread abort, you'll get a ThreadAbortException in your thread, so if you put it in the finally clause, it will get set even in the case of a thread abort.
The situation is as follows: a thread timer (from System.Threading.Timer) runs in an interval and use a object to lock and do something. An UI timer (System.Windows.Forms.Timer) do also thinks on the form by interval and using the same object. So he locks this object also.
Sometimes the thread timer will do invoke the UIThread as follow:
lock (_lockobj)
{
form.Invoke(new MethodInvoker(delegate
{ // Do somethings on form }));
}
The problem is that this call will 'sleep' because the same lock on '_lockobj' is happen by the Form timer (which sleep also). So a deadlock is happen (this is what it is?).
I think it is clearly for me what is happening here but how to solve this. Or is this a design failure? Or maybe there are functions available that help me with this?
Question is: is it maybe possible that a not-UIThread invoking the form when the UIThread is sleeping?
Thanks.
This is clearly a deadlock. You must not call into other thread while holding a lock.
Explanation:
Imagine that the timer thread gets the lock, and is going to call to the UI thread. At the very same moment, the UI thread is trying to obtain the lock, and now waits for it to be released. So return to the first thread: the call into the UI thread cannot finish, because the UI thread is waiting. Deadlock.
My suggestion would be: get rid of all locking, and marshal all the operations into the UI thread. This way your calls are obviously serial (all of them happen in the same thread!), so there's no need for locking.
Thread.Join returns us if the thread has completed. The same we can determine using ThreadState. Then what is the difference between Thread.Join() and Thread.ThreadState?
Can we use them interchangeably?
The difference between Join and looking at ThreadState manually is that Join is a blocking operation. The function won't return until the timeout is reached or the target Thread completes. Checking the ThreadState is more of a peeking operation.
Thread.join WAITS for the thread to complete. ThreadState just gives you a snapshot of the thread and returns without waiting. There's also a variant of Thread.join that takes a time to wait. ThreadState and Join are extremely different and I don't think both can be used interchangeably.
Try doing a test where you do both calls on a thread that has an infinite loop.
When you call Thread.Join() it blocks the calling thread until the thread that has Join method is completed. If it is aborted, or successfully completed, Join() that follows will not block the calling thread. This allows you to have 10 worker threads and one main thread which operation must be run after all 10 threads completed. So you can call Join() on the first thread. That call will block the main thread until first working thread completes. After that you can call Join() on second thread, and so on until you get to thread #10. When you call Join() on it, and main thread gets resumed, you can be sure that all 10 threads completed and main thread can resume its operation.
For example:
Thread workers[] = new Thread[10];
//*** create and start threads ***
foreach(Thread worker in workers)
{
worker.Join();
}
//All threads are completed, now this operation can continue...
On the other hand, Thread.ThreadState only returns the thread status (Aborted, Running, ...) without affecting the calling thread's state (not as Join which puts the calling thread in WaitSleepJoin state). So this is for use only if you want to check whats happening with thread so you can take a certain action, or you want to implement your own Join mechanism, and so on...
Thread.Join will block the calling thread
I've got a queue, which is basically the producer/consumer queue in the albahari.com
threading book, which takes an queue item off the queue, which is an action execution block off the queue and then calls a method to execute the actionlist within the queue item.
I can kill the queue easily enough by enqueing a null actionblock and block the main thread by doing a spin/wait with a thread.sleep() until the queue count goes to zero, and all the threads fall through the while !=null loop, thereby completing, but the method executing the last actionlist may still be executing the last thread.
Question is, is their anyway to detect if that method still has a thread executing it, like maybe using a Semaphore or counter with an Interlock to count the semaphore up at the beginning of the method and count it down at the end. So if it reaches zero, them I know its not threaded.
This is the implementing a destroy method on the interface, to close it down before calling dispose.
Use the Backgroundworker which has a completed event
If you start a thread like this:
System.Threading.Thread mythread = new System.Threading.Thread();
mythread.Start();
You can check:
mythread.IsAlive()
at any point to determine its status.
Use a PostSharp attribute on the method.