|
|
Hello
i créate 10 threads to do a task.
i create a Semapohre to limit access at compteur by 3 threads
how to lock data (compteur)
namespace threads
{
class Program
{
public static int compteur;
public static object ob = new object();
public static SemaphoreSlim sem = new SemaphoreSlim(3);
public static void Thread_test() {
sem.Wait();
for (int i = 0; i < 1000000; i++)
{
compteur++;
}
sem.Release();
System.Console.WriteLine(compteur.ToString());
}
static void Main(string[] args)
{
Thread[] th = new Thread[10];
for (int i = 0; i < th.Length; i++)
{
th[i] = new Thread(Thread_test)
{
Name = "thread_" + i
};
th[i].Start();
}
System.Console.ReadLine();
}
}
}
Result:
thread_2 = 1264634
thread_0 = 1440996
thread_1 = 1645012
thread_3 = 2344585
thread_5 = 2694858
thread_4 = 2809001
thread_6 = 3628891
thread_8 = 3651918
thread_7 = 3991965
thread_9 = 4527904
and i want this without lock function just with Semaphore:
thread_3 = 1893992
thread_1 = 2735536
thread_4 = 4274643
thread_2 = 4349873
thread_0 = 6248051
thread_5 = 7430503
thread_6 = 8107979
thread_7 = 8937401
thread_9 = 9815069
thread_8 = 10000000
Thank you so much
|
|
|
|
|
Don't cross post: you already have this in QA, so posting it in multiple places just duplicates work and that annoys people. Pick one place, and stick to it.
Sent from my Amstrad PC 1640
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Based on the time-stamps, the copy in QA is the repost.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
You have up to three threads modifying the same shared variable at the same time, without any coordination. This will not end well.
For example:
Thread 0: Read compteur == 0
Thread 1: Read compteur == 0
Thread 0: Update compteur = compteur + 1 == 1
Thread 2: Read compteur == 1
Thread 2: Update compteur = compteur + 1 == 2
Thread 1: Update compteur = compteur + 1 == 1
Three threads have incremented the same variable, but the value has only increased by 1 .
Things get even more complicated when you start considering memory models, CPU cache, speculative execution, ...
To safely increment the value within your thread, you need to use Interlocked.Increment[^]:
public static void Thread_test()
{
sem.Wait();
int result = 0;
for (int i = 0; i < 1000000; i++)
{
result = Interlocked.Increment(compteur);
}
sem.Release();
System.Console.WriteLine(result);
}
To do anything more complicated, you will need to use locks or other coordination primitives to prevent the shared state from being modified by multiple threads at the same time.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
thank you for your answer,
I understand the principle for the increment.
if i understand Semaphore can just manage the number of threds to acces the data, but dont manage the lock of the data to use it.
it is necessary to use lock or other to lock the data? or i(t possible to do that with semaphore
Here i use an compteur for example.
i see a lot of youtube'movie but i'don't find a complete toturiel with lock mutex moniter somaphore threads.
thank you
|
|
|
|
|
The point is that your semaphore allows three threads to run the protected code block at the same time. All three threads are trying to modify the same shared state at the same time.
The ++ operator is not atomic - it reads the value, increments it, and writes it back, which takes three operations. With multiple threads, those operations can be interleaved, resulting in incorrect behaviour.
The Interlocked.Increment operator is atomic. No other thread can sneak code into the middle of the operation.
(Interlocked operations using a 64-bit type on a 32-bit OS will only be atomic with respect to each other. Accessing the value without using the Interlocked class will still have problems.)
For anything more complicated that a single numeric variable, you need to use some kind of coordination primitive to protect the shared state. What you use will depend on how the state will be accessed. For example, if most accesses are reading the state, and only a few are modifying the state, a ReaderWriterLockSlim[^] would probably be a good choice.
Ultimately, the best option is to avoid shared state wherever possible.
Threading in C# - Part 2 - Basic Synchronization[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
i am trying to make the simplest c# application - connect to the LG TV and send a command like KEY_UP.
the tv is using WEBOS 3.0 and it is possible to connect and control it using android remote when they are connected to the same network via wifi.
this is an example i found on the net:
LG tv app to display the list of messages - Stack Overflow[^]
i tried posting the json using postman to the TV's address and it replies with "hello world".
i have no idea how to pair with it in order to be able to make the command or any other command work.
Have anyone done this and can point me to an example? i couldn't find one that can help with this and LG doesn't seem to have client SDK for .net.
|
|
|
|
|
Is it worth having a look at the SDK itself?
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
|
|
|
|
|
|
What UI are you writing for?
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
MyCroft is right - we need to know which UI you are working with, because there are different ListView controls for WinForms, WPF, websites, etc. and any solution will depend on exactly which one you are trying to use.
Sent from my Amstrad PC 1640
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I'm looking for an example of highlighting cell the listView of winform or an example of an employee timestamp based on the listView cell color, you can see the attached image file above.
|
|
|
|
|
I have a problem with making a simple SelectedIndex to work with the SelectionChanged.
The same piece of code worked perfectly well with the button click as the event handler but it doesn't work with the selection changed...
All I want is to have a ComboBox with a default value selected,
TextBox displaying this value below, and changing every time I change the selection.
<ComboBox x:Name="BetonCombo" Margin="5" Grid.Column="0" Padding="2" HorizontalAlignment="Center" Width="150" SelectedValuePath="Content" SelectionChanged="BetonCombo_SelectionChanged">
<ComboBoxItem>C16/20 (B20)</ComboBoxItem>
<ComboBoxItem>C20/25 (B25)</ComboBoxItem>
<ComboBoxItem>C25/30 (B30)</ComboBoxItem>
<ComboBoxItem IsSelected="True">C30/37 (B37)</ComboBoxItem>
<ComboBoxItem>C35/45 (B45)</ComboBoxItem>
</ComboBox>
private void BetonCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int mBetonIndex = BetonCombo.SelectedIndex;
double[] Fck = new double[5];
Fck[0] = 20;
Fck[1] = 25;
Fck[2] = 30;
Fck[3] = 37;
Fck[4] = 45;
double mFck = Fck[mBetonIndex];
fck.Text = mFck.ToString() + " MPa";
}
I am getting this exception
System.NullReferenceException: 'Object reference not set to an instance of an object.' with the last line of code highlighted as the problem (fck.Text = mFck.ToString() + " MPa";).
I don't understand how I could get a null reference if the exact same code worked perfectly fine in the button click event handler? Do I need to set a default value of the ComboBox differently than with a IsSelected=true?
|
|
|
|
|
You get a null reference, probably because C# is case sensitive.
So fck is not the same as Fck and the chances are that when you SelectionChanged event happens, the rest of your code hasn't done anything useful with fck yet. But we can't see the code, so we can't help.
So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger.
Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.
Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
Sent from my Amstrad PC 1640
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Haha, thanks Debugging is actually the next thing I was about to get into.
But actually I found out what was the problem with my code, but it's very strange.
When I removed the IsSelected="true" from the ComboBox item parameters, everything works just fine.
It looks like the SelectionChanged event handler is fired by itself at the start of the program when the IsSelected parameter is resolved...
but now I have no default value in my combo box at the start of the program tho
|
|
|
|
|
Well yes, of course it is!
And it comes in with an SelectedIndex value of -1 to tell you "there is nothing selected"
So reset the property, and try checking for a negative index!
Sent from my Amstrad PC 1640
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Looks like code from TMS?
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Eddy Vluggen wrote: Looks like code from TMS
Teenage Mutant Sparrows?
Sent from my Amstrad PC 1640
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
A company that I used to work which automated concrete-factories; didn't have much coding-guidelines in those days, but terms like "f***" were forbidden because it looks sh*tty during a presentation.
So, one of the coworkers started using variable names like "fck" and "yf" (standing for yuck fou).
Good memories
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
It's not for any company, just my own little project to make life easier
In general the purpose of this program is going to be calculating the stirrup spacing and longitudinal reinforcement in a concrete beam subjected to shear and torsion.
Btw, I have another problem to solve... is there any easy way to create method inside a class that would automatically add a property of this instance to a list?
For example I have a class:
class Beton
{
public string Label { get; set; }
public double Fck { get; set; }
public double Fcm { get; set; }
public double Fctm { get; set; }
public double Ecm { get; set; }
{
}
}
Now I want to make 3 instances of this class:
Beton B20 = new Beton();
B20.Label = "C16/20 (B20)";
B20.Fck = 20;
Beton B25 = new Beton();
B25.Label = "C20/25 (B25)";
B25.Fck = 25;
Beton B30 = new Beton();
B30.Label = "C25/30 (B30)";
B30.Fck = 25;
and I want that the list below would be automatically created when I instantiate a class:
List<string> comboBoxList = new List<string>();
comboBoxList.Add(B20.Label);
comboBoxList.Add(B25.Label);
comboBoxList.Add(B30.Label);
comboBoxList.Add(B37.Label);
Is this possible?
|
|
|
|
|
Yes:
public class Beton
{
private static List<Beton> all = new List<Beton>();
public Beton()
{
...
all.Add(this);
}
} Because the collection is static there is only one instance of teh collection which is shared by all instances of the Beton Class.
Sent from my Amstrad PC 1640
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Thank you for the answer.
It looks like I am still missing something, I got the error that my list doesn't exist in the current context in the main window.
Is something more supposed to be in the "..." place in your snippet?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Beton B20 = new Beton();
B20.Nazwa = "C16/20 (B20)";
B20.Fck = 20;
Beton B25 = new Beton();
B25.Nazwa = "C20/25 (B25)";
B25.Fck = 25;
Beton B30 = new Beton();
B30.Nazwa = "C25/30 (B30)";
B30.Fck = 25;
Beton B37 = new Beton();
B37.Nazwa = "C30/37 (B37)";
B37.Fck = 37;
BetonCombo.ItemsSource = comboBoxList;
public class Beton
{
public string Label { get; set; }
public double Fck { get; set; }
public double Fcm { get; set; }
public double Fctm { get; set; }
public double Ecm { get; set; }
private static List<Beton> comboBoxList = new List<Beton>();
public Beton()
{
comboBoxList.Add(this);
}
}
|
|
|
|
|
That's because it's a part of the Beton class, not the MainWindow class.
If you want to access the collection, then I'd provide a get-only property (or a GetAll method) which returns a copy of the list as part of the Beton Class:
public class Beton
{
public static List<Beton> All
{ get { return new List<Beton>(all);} }
...
} That way, the outside world can't mess with your collection!
Sent from my Amstrad PC 1640
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
modified 4-Aug-18 10:09am.
|
|
|
|
|
I tried to get this to work, but I had to give up after like 3 hours.
For now I left a manually declared list after instantiating the class.
In general I got the "cannot implicitly convert Beton to String", or "Beton to Int", or "List<string> to string", etc, whie trying different ways of writing this.
I don't really know what should be the output of using class name as the List Type (as in List < Beton>) and adding .Add(This) to it. Is it supposed to add every property of the instantiated class as an object regardless of its type to the List?
I am looking for some good toutorial about types accepted by the List object, etc. Is there something you could recommend? For now I didn't find anything thorough enough.
Anyway, thanks for posting, I will do some more search on it in free time.
modified 4-Aug-18 18:17pm.
|
|
|
|