c#


Can this code cause a dead lock ?


using System;
using System.Threading;
namespace Threading
{
class Program
{
static void Main(string[] args)
{
Semaphore even = new Semaphore(1, 1);
Semaphore odd = new Semaphore(1, 1);
Thread evenThread = new Thread(() =>
{
for (int i = 1; i <= 100; i++)
{
even.WaitOne();
if(i % 2 == 0)
{
Console.WriteLine(i);
}
odd.Release();
}
});
Thread oddThread = new Thread(() =>
{
for(int i = 1; i <=100; i++)
{
odd.WaitOne();
if(i%2 != 0)
{
Console.WriteLine(i);
}
even.Release();
}
});
oddThread.Start();
evenThread.Start();
}
}
}
So I have written this code where one thread is producing Odd numbers and other is producing even numbers.
Using Semaphores I have made sure that they print numbers in orders and it works perfectly.
But I have a special situation in mind, for example each thread waits until the other thread releases its semaphore. So can there be a condition where both threads are waiting and no thread is making any progress and there is a deadlock situation ?
For deadlock to occur, two or more threads must be trying to acquire two or more resources, but do so in different orders. See e.g. Deadlock and Would you explain lock ordering?.
Your code does not involve more than one lock per thread† and so does not have the ability to deadlock.
It does have the ability to throw an exception. As noted in this comment, it is theoretically possible for one of the threads to get far enough ahead of the other thread that it attempts to release a semaphore lock that hasn't already been taken. For example, if evenThread is pre-empted (or simply doesn't get scheduled to start running) before it gets to its first call to even.WaitOne(), but oddThread gets to run, then oddThread can acquire the odd semaphore, handle the if statement, and then try to call even.Release() before evenThread has had a chance to acquire that semaphore.
This will result in a SemaphoreFullException being thrown by the call to Release().
This would be a more likely possibility on a single-CPU system, something that is very hard to find these days. :) But it's still theoretically possible for any CPU configuration.
† Actually, there's an implicit lock in the Console.WriteLine() call, which is thread-safe by design. But from your code's point of view, that's an atomic operation. It's not possible for your code to acquire that lock and then wait on another. So it doesn't have any relevance to your specific question.

Related Links

How to assign a value from MemberExpression to a field according to another MemberExpression?
Is calling a static method from an instance method thread safe?
HTTP Error 404.0 - Not Found in Mvc 6 Asp.net 5
Read Bytes Into Stream One Page At A Time C#
Clipboard.GetImage() returning null
Passing variable from C# to PowerShell does not work
404 implementation in MVC Razor
Connecting Unity3D to SQL [CodePage 1256 not supported]
Using Azure Active Directory - one application to login locally and when published
The best overloaded Method has some invalid arguments and Cannot convert type
Detecting a PowerShell Switch
Re-prioritize items in a rabbitMq priority queue
c# DataGridView get Cells Value from Selected Row
How do I fix CS0433 errors in ASP.NET 5?
excel interop variable range
Event logger in Windows 10 Universal Apps

Categories

HOME
actionscript-3
airflow
spring-boot
macros
android-ndk
gaussian
mailchimp
snmp
powerquery
uml-designer
swap
meson-build
genexus
jcodemodel
ng2-charts
element
minimum
infopath
dat.gui
bookmarklet
taxonomy
alert
md2
minimagick
procedural-generation
devexpress-mvc
policy
ps
priority-queue
angular2-changedetection
sqldependency
git-submodules
pypy
semantic-ui-react
mobile-development
qt-designer
node-soap
offset
sdl-2
abide
realloc
stencyl
yelp
libconfig
linkurious
usernotifications
paperclip
pexpect
chrome-custom-tabs
runner
easyquery
visio-2010
htop
fckeditor
multi-targeting
robotc
recursive-query
alarmmanager
timefield
mongodb-3.3
vga
nsoperationqueue
aws-kms
database-administration
abstract
code-translation
commercetools
lytro
page-flipping
textblob
stderr
system.diagnostics
sicstus-prolog
ultraedit
alpha-beta-pruning
method-overloading
random-access
information-hiding
novell
lwuit
cocos2d-x-2.x
kuka-krl
mongoid4
mdp
node-amqp
nop
mencoder
ie-developer-tools
typography
usersettings
backbone-views
urlfetch
rfc822
gssapi
jquery-ui-map
wxperl
parsec
scriptmanager
method-call
hwnd
javah
mass-emails
onunload
iphone-maps
p4.net
system-analysis
calendarextender
managed-code

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App