This question already has answers here:
Why is lock(this) {...} bad?
(18 answers)
Closed 8 years ago.
I wanted to understand dangers of lock(this) with some code example. With the code, if everything works well I expect to see 1000 at the end of program.
And that's what I get every time I run it even though I am using lock(this). Why lock(this) works well here?
class Program
{
static void Main(string[] args)
{
Test t = new Test();
for (int x = 0; x < 100; x++)
{
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++)
{
threads[i] = new Thread(t.ProtectedMethod);
threads[i].Start();
}
for (int i = 0; i < 10; i++)
threads[i].Join();
Console.WriteLine("Done with {0}", t.i);
}
}
}
class Test
{
public int i = 0;
public void ProtectedMethod()
{
lock (this)
{
i++;
}
}
}
The lock on this prevents multiple threads to enter the lock code block for the object at the same time. While one thread is in the code block, the other threads are waiting until the current lock on 'this' object is released.
It runs okay because example is too simple. It's equivalent to the case when you lock on some private variable. I say that it will even run fine if you wrap for loop with lock (t) since lock supports recursion.
But imagine if other thread had locked on your variable and entered some infinite loop? Just after you created variable? A deadlock would occur.
Now let's imagine you provide your code with lock (this) as 3rd party dll. You never know how smart will be the consumer of your library...
Related
This question already has answers here:
Captured variable in a loop in C#
(10 answers)
Closed 3 months ago.
Been working on a program recently and have a question about a problem I ran into. I've solved it, but don't know why it's happening:
for(int i = 0; i<10; i++)
{
Thread t = new Thread (() => {(does stuff, uses "i")});
}
Essentially I have 10 known processes I want to run on separate threads. In the thread, the value of the incrementor "i" is used to assign an object to a position in another array (I use locking). Now if I run it as is, I get an out of bounds error and when I debug with code breaks, I find that on that last loop i is equal to 10, when the last value should be 9. When this code isn't threaded, it works perfectly fine.
I decided to try and assign the incrementer to a local variable inside the thread:
for(int i = 0; i<10; i++)
{
Thread t = new Thread (() =>
{
localI=i;
(does stuff, uses "localI")
});
}
This had the same issue. I did more reading online and tried a different ordering of it:
for(int i = 0; i<10; i++)
{
localI=i;
Thread t = new Thread (() =>
{
(does stuff, uses "localI")
});
}
And this code works. I can't at all figure out why this works, but the second example didn't. Could anyone help me figure it out?
Thanks
Effectively there are 11 threads, your main thread running the for loop and the threads you spawn.
By the time your 10 new threads run the main loop might well be finished and the value of i will be 10. If you then use this to index an array you will get the out of bounds error.
Your third example assigns i to the localI var, this will keep its value and the individual threads will use that saved value of localI.
It`s simple.
The i variable is run on main thread and for loop reaches 10 value even before the child thread initiates. So, you can add a local variable outside of child threads to get fixed value on every loop.
And, for loop set 10 on i variable, but not run loop, because gets false on checks.
Simple test:
class Program
{
static void Main(string[] args)
{
Test c = new Test();
Console.WriteLine("NonLocal:");
Console.WriteLine(string.Join(",", c.NonLocal));
Console.WriteLine();
Console.WriteLine("Local:");
Console.WriteLine(string.Join(",", c.Local));
Console.ReadLine();
}
}
class Test
{
public object locker;
public List<object> NonLocal; // use List<> for dynamic array
public object[] Local;
public Test()
{
this.locker = new object();
this.NonLocal = new List<object>();
this.Local = new object[10];
// child thread pool
List<Thread> threads = new List<Thread>();
for (int i = 0; i < 10; i++)
{
int localI = i;
Thread t = new Thread(() =>
{
lock (locker)
{
// adding to result only index
// to see value on i variable on this point
this.NonLocal.Add(i);
// using a fixed local variable
this.Local[localI] = localI;
}
});
threads.Add(t);
t.Start();
}
// wait until threads end
while (true)
{
if (!threads.Any(x => x.IsAlive)) break;
}
}
}
This question already has answers here:
C# "lock" keyword: Why is an object necessary for the syntax?
(3 answers)
Closed 4 years ago.
I do not speak English and I use translator.
I'm wondering when I'm studying thread synchronization.
class MainApp
{
static public int count = 0;
static private object tLock = new object();
static void plus()
{
for (int i = 0; i < 100; i++)
{
lock (tLock)
{
count++;
Console.WriteLine("plus " + count);
Thread.Sleep(1);
}
}
}
static void minus()
{
for (int i = 0; i < 100; i++)
{
lock (tLock)
{
count--;
Console.WriteLine("minus " + count);
Thread.Sleep(1);
}
}
}
static void Main()
{
Thread t1 = new Thread(new ThreadStart(plus));
Thread t2 = new Thread(new ThreadStart(minus));
t1.Start();
t2.Start();
}
}
Simple thread studying.
static private object tLock = new object();
lock (tLock) << argument value, why object argument??
Why have an object argument on lock?
Well, because it's convenient.
First of all, it's obvious in your code example that you need some shared state between the calls to lock, to declare that two different sections of code are mutually exclusive. If the syntax was just lock { } without a parameter, like this:
public void DoSomestuff()
{
lock
{
// Section A
}
}
public void DoOtherStuff()
{
lock
{
// Section B
}
}
Then either all locks would be mutually exclusive, or would impact only their individual portion of code (so two threads could execute section A and B concurrently, but only one thread at a time could execute A). This would greatly reduce the usefulness of the keyword.
Now that we established that we need a shared state, what this state should be? We could have used a string:
lock ("My Section")
{
// Section A
}
It would work but has a few drawbacks:
You expose yourself to potential collisions between the name of different sections in different libraries
It means that the runtime has to keep a kind of table to associate the string to a lock. Nothing too difficult, but that's some overhead
Instead, the .NET authors went for using an object argument. This solves problem 1/, as you know that another library won't have a reference to your object unless you willingly give it. But this also solves problem 2/, because this allows the runtime to store the lock in the actual object header. That's a pretty neat optimization.
Consider the following (without lock):
for (int i = 0; i < 1000; i++)
{
count++;
Console.WriteLine("plus " + count);
Thread.Sleep(1);
}
If two threads run simultaneously:
First thread adds one to count which is now 1.
Now second thread takes over and adds one to count which is now 2.
Second thread continues to print plus 2 and loops and again adds one to count which is now 3.
Now the first thread takes over and prints plus 3 which was not intended since count was 1 when WriteLine was to be called.
When adding a locking mechanism (lock) the developer makes sure that a part of the code is atomic, i.e. is run in sequence without interruption.
for (int i = 0; i < 1000; i++)
{
lock (tLock)
{
count++;
Console.WriteLine("plus " + count);
Thread.Sleep(1);
}
}
If you follow the same pattern here:
First thread adds one to count which is now 1.
Now second thread tries to take over but has to wait until the lock is released by the first thread.
First thread prints plus 1 and releases the lock.
Now second thread can take over and add one to count which is now 2.
First thread tries to take over but has to wait until the second thread releases the lock.
Second thread prints plus 2 and releases the lock.
As you can see the increment and WriteLine are now synchronized operations.
Edit
After you changed the question:
The lock keyword requires an object of reference type. It doesn't have to be an object. It can also be a class, interface, delegate, dynamic or string.
public static string a = string.Empty;
public static void Main()
{
lock(a)
{
Console.WriteLine("Hello World");
}
}
See the documentation for more information.
This question already has answers here:
Captured variable in a loop in C#
(10 answers)
Closed 6 years ago.
Fire and forget method in C#
I refered different issues for 'Fire and Forget in C#'
i.e.
Simplest way to do a fire and forget method in C#?
.
.
and few several,
but i have an another issue with the same.i wrote following code
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
//fireAway(i);
Task.Factory.StartNew(() => fireAway(i));
}
Console.WriteLine("Main Finished");
Console.Read();
}
public static void fireAway(int i)
{
System.Threading.Thread.Sleep(5000);
Console.WriteLine("FireAway" + i);
}
where i am expecting output like
Main Finished
FireAway0
FireAway1
FireAway2
FireAway3
FireAway4
but output is
Main Finished
FireAway5
FireAway5
FireAway5
FireAway5
FireAway5
very honestly i am new to threading concept, i need help. How can i meet with expected output..?
The threads are started after the loop is finished. When the loop is finished the value of i is 5. You have to capture the value of i before you send it to StartNew(..)
for (int i = 0; i < 5; i++)
{
int tmp = i;
Task.Factory.StartNew(() => fireAway(tmp));
}
You should pass parameter to your method, not use i, because the method will start to execute only after you finish to iterate, see here
How can I run the code below in LinqPad as C# Program Thank you...
class ThreadTest
{
static void Main()
{
Thread t = new Thread (WriteY); // Kick off a new thread
t.Start(); // running WriteY()
// Simultaneously, do something on the main thread.
for (int i = 0; i < 1000; i++) Console.Write ("x");
}
static void WriteY()
{
for (int i = 0; i < 1000; i++) Console.Write ("y");
}
}
Result Expected
xxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ...
So far I came up with
static void Main()
{
Thread t = new Thread (ThreadTest.WriteY); // Kick off a new thread
t.Start(); // running WriteY()
// Simultaneously, do something on the main thread.
for (int i = 0; i < 1000; i++) Console.Write ("x");
}
class ThreadTest
{
public static void WriteY()
{
for (int i = 0; i < 1000; i++) Console.Write ("y");
}
}
Actual Result
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy...
As seen on Result Expected it should be mixed X and Y.
Unfortunately Actual Result is 1000 times X and 1000 times Y
UPDATE
This sample - along with all the others in the concurrency chapters of C# 5 in a Nutshell are downloadable as a LINQPad sample library. Go to LINQPad's samples TreeView and click 'Download/Import more samples' and choose the first listing. – Joe Albahari
Thread switching is by nature non-deterministic. I can run your program multiple times and get varying results.
If you want the switching to be more evident, add some pauses:
static void Main()
{
Thread t = new Thread (ThreadTest.WriteY); // Kick off a new thread
t.Start(); // running WriteY()
// Simultaneously, do something on the main thread.
for (int i = 0; i < 1000; i++)
{
Console.Write ("x");
Thread.Sleep(1);
}
}
class ThreadTest
{
public static void WriteY()
{
for (int i = 0; i < 1000; i++)
{
Console.Write ("y");
Thread.Sleep(1);
}
}
}
I cannot explain why this works, but changing to using Dump() seems to make it behave like the OP wants with the x's and y's "mixed" with every run (although with newlines between every output):
void Main()
{
Thread t = new Thread (ThreadTest.WriteY); // Kick off a new thread
t.Start(); // running WriteY()
// Simultaneously, do something on the main thread.
for (int i = 0; i < 1000; i++) "x".Dump();
}
class ThreadTest
{
public static void WriteY()
{
for (int i = 0; i < 1000; i++) "y".Dump();
}
}
From the LinqPAD documentation:
LINQPad's Dump command feeds the output into an XHTML stream which it
displays using an embedded web browser (you can see this by
right-clicking a query result and choosing 'View Source'. The
transformation into XHTML is done entirely using LINQ to XML, as one
big LINQ query! The deferred expansion of results works via
JavaScript, which means the XHTML is fully prepopulated after a query
finishes executing. The lambda window populates using a custom
expression tree visitor (simply calling ToString on an expression tree
is no good because it puts the entire output on one line).
I also know that LinqPAD overrides the default Console.WriteLine behavior, so perhaps that has something to do with it.
I have a main thread which is controlling a windows form, upon pressing a button two threads are executed. One is used for recording information, the other is used for reading it. The idea behind putting these in threads is to enable the user to interact with the interface while they are executing.
Here is the creating of the two threads;
Thread recordThread = new Thread(() => RecordData(data));
recordThread.Name = "record";
recordThread.Start();
Thread readThread = new Thread(() => ReadData(data));
readThread.Name = "read";
readThread.Start();
The data is simply a Data-object that stores the data that is recorded during the recording.
The problem that I am facing is that the first thread is executed fine, the second refuses to run until the first one completes. Putting a breakpoint in the second threads function, ReadData lets me know that it is only called after the first thread is done with all of its recording.
I have been trying to solve this for a few hours now and I can't get my head around why it would do this. Adding a;
while(readThread.IsAlive) { }
right after the start will halt the execution of anything after that, and it's state is Running. But it will not go to the given method.
Any ideas?
Edit:
The two functions that are called upon by the threads are;
private void RecordData(Data d)
{
int i = 0;
while (i < time * freq)
{
double[] data = daq.Read();
d.AddData(data);
i++;
}
}
private void ReadData(Data d)
{
UpdateLabelDelegate updateData =
new UpdateLabelDelegate(UpdateLabel);
int i = 0;
while (i < time * freq)
{
double[] data = d.ReadLastData();
this.Invoke(updateData, new object[] { data });
i++;
}
}
The data object has locking in both the functions that are called upon; ReadLastData and Read.
Here are the methods in the Data object.
public void AddData(double[] data)
{
lock (this)
{
int i = 0;
foreach (double d in data)
{
movementData[i].Add(d);
i++;
}
}
}
public double[] ReadLastData()
{
double[] data = new double[channels];
lock (this)
{
int i = 0;
foreach (List<double> list in movementData)
{
data[i] = list[list.Count - 1];
}
}
return data;
}
Looks like you have a race condition between your reading/writing. In your first thread you lock down the object whilst you add data to it and in the second thread you attempt to get an exclusive lock on it to start reading. However, the problem is the first thread is executing so fast that the second thread never really gets a chance to acquire the lock.
The solution to this problem really depends on what sort of behaviour you are after here. If you expect after every write you get a consecutive read then what you need to do is control the execution between the reading/writing operations e.g.
static AutoResetEvent canWrite = new AutoResetEvent(true); // default to true so the first write happens
static AutoResetEvent canRead = new AutoResetEvent(false);
...
private void RecordData(Data d)
{
int i = 0;
while (i < time * freq)
{
double[] data = daq.Read();
canWrite.WaitOne(); // wait for the second thread to finish reading
d.AddData(data);
canRead.Set(); // let the second thread know we have finished writing
i++;
}
}
private void ReadData(Data d)
{
UpdateLabelDelegate updateData =
new UpdateLabelDelegate(UpdateLabel);
int i = 0;
while (i < time * freq)
{
canRead.WaitOne(); // wait for the first thread to finish writing
double[] data = d.ReadLastData();
canWrite.Set(); // let the first thread know we have finished reading
this.Invoke(updateData, new object[] { data });
i++;
}
}
Could you try adding a Sleep inside RecordData?
Maybe it's just your (mono cpu??) windows operating system that doesn't let the second thread get its hand on cpu resources.
Don't do this:
lock (this)
Do something like this instead:
private object oLock = new object();
[...]
lock (this.oLock)
EDIT:
Could you try calls like this:
Thread recordThread = new Thread((o) => RecordData((Data)o));
recordThread.Name = "record";
recordThread.Start(data);