ManualResetEvent ManualResetEventSlim and Thread.Yeild

November 19, 2019 Leave a comment

Is there a difference in the behavior of a Thread when waking from a ManualResetEvent vs a ManualResetEventSlim when Thread.Yeild is involved? Yes, there is a difference in behavior!

The scenario is: If threads are woken up by an event and then call Thread.Yeild, does that Thread.Yeild wait for all of the threads to be woken up? With ManualResetEvent the answer is Yes, and the answer for ManualResetEventSlim the answer is No.

I wrote a little program in C# to test this out and was surprised by the difference in behavior. When using the ManualResetEventSlim, a Thread would wake up, Yield, and reset the slim event, before most of the other threads even woke up. As a result a single thread would be blocked behind the ManualResetEventSlim during multiple calls to Set and Reset. I’m guessing that the difference in behavior is due to the spin waits that ManualResetEventSlim does. The spins will sleep a Thread, and as a result Thread.Yield won’t wait for those threads.

The other thing that I learned in this program is that even though a Thread calls Thread.Start on another Thread, that doesn’t mean that its next call to Thread.Yeild will actually wait for the other Thread to be started.

Here is the program configured to use ManualResetEvent. If you want to see the behavior for ManualResetEventSlim change the type for the e variable, and switch the calls to WaitOne to Wait.

class Program
{
private static int counter = 0;
private static ManualResetEvent e = new ManualResetEvent(false);
static void Main(string[] args)
{
var threads = new Thread[20];
var allLogs = new List<List<Tuple<int,string>>>(21);
for (int i = 0; i < threads.Length; ++i)
{
var t = new Thread(obj =>
{
var logs = new List<Tuple<int, string>>();

int log = Interlocked.Increment(ref counter);
logs.Add(new Tuple<int, string>(log, "Waiting 1"));
e.WaitOne();
Thread.Yield();
e.Reset();

log = Interlocked.Increment(ref counter);
logs.Add(new Tuple<int, string>(log, "Waiting 2"));
e.WaitOne();
Thread.Yield();
e.Reset();

log = Interlocked.Increment(ref counter);
logs.Add(new Tuple<int, string>(log, "Waiting 3"));
e.WaitOne();
Thread.Yield();
e.Reset();

log = Interlocked.Increment(ref counter);
logs.Add(new Tuple<int, string>(log, "Waiting 4"));
e.WaitOne();
log = Interlocked.Increment(ref counter);
logs.Add(new Tuple<int, string>(log, "Done"));

lock (allLogs)
{
allLogs.Add(logs);
}
});
t.Start();
threads[i] = t;
}
try
{
var mainLogs = new List<Tuple<int, string>>();
int mainLog = Interlocked.Increment(ref counter);
mainLogs.Add(new Tuple<int, string>(mainLog, "Main Yeild"));
Thread.Yield();
mainLog = Interlocked.Increment(ref counter);
mainLogs.Add(new Tuple<int, string>(mainLog, "Main Setting 1"));
e.Set();
Thread.Sleep(TimeSpan.FromSeconds(1));
mainLog = Interlocked.Increment(ref counter);
mainLogs.Add(new Tuple<int, string>(mainLog, "Main Setting 2"));
e.Set();
Thread.Sleep(TimeSpan.FromSeconds(1));
mainLog = Interlocked.Increment(ref counter);
mainLogs.Add(new Tuple<int, string>(mainLog, "Main Setting 3"));
e.Set();
Thread.Sleep(TimeSpan.FromSeconds(1));
mainLog = Interlocked.Increment(ref counter);
mainLogs.Add(new Tuple<int, string>(mainLog, "Main Setting 4"));
e.Set();
Thread.Sleep(TimeSpan.FromSeconds(1));
mainLog = Interlocked.Increment(ref counter);
mainLogs.Add(new Tuple<int, string>(mainLog, "Main Setting 5"));
e.Set();

bool allStopped = false;
while (allStopped == false)
{
allStopped = true;
for(int i = 0; i < threads.Length; ++i)
{
if (!(threads[i].ThreadState == ThreadState.Stopped || threads[i].ThreadState == ThreadState.StopRequested))
{
allStopped = false;
mainLog = Interlocked.Increment(ref counter);
mainLogs.Add(new Tuple<int, string>(mainLog, "Main Thread " + i + " is not Stopped"));
e.Set();
Thread.Yield();
break;
}
}
}

lock (allLogs)
{
allLogs.Add(mainLogs);
}

var logTuples = from logCollection in allLogs
from logTuple in logCollection
orderby logTuple.Item1
select logTuple;

foreach(var lt in logTuples)
{
Console.WriteLine($"{lt.Item1}\t{lt.Item2}");
}
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
}
}

 

The Dangers of the 51 Percent Majority

November 15, 2019 Leave a comment

It is very natural to come up with a system where decisions are made by the majority. There is a vote and the side that gets the most votes wins the decision. Most of the time it works really well. Well enough that there can be little motivation to do otherwise. After all, it wouldn’t make sense to let the minority make decisions. That just isn’t sustainable. On the other hand, if the minority is completely shut out, that leads to problems in the long run. There is a phrase that exists, called the Tyranny of the Majority, and checks and balances have been put in place to counter it in government, but I fear that the ones currently in place are insufficient.

Starting with a non-government example consider the current state of Sears. For a century, Sears dominated the American consumer economy. In the last two decades though, it has completely fallen apart. One major reason is due to decisions made by the current majority stockholder. That right, not holders; holder. It’s a problem that one individual controls 51 percent of the company. Normally one might think that that wouldn’t be a problem, because the majority owner would want the company to succeed. But that is not the case with Sears.

The person who owns 51 percent of the stock, didn’t buy up all of that control of the company to see it succeed, they did it to make sure that it failed in the right way. That individual owns other companies too. Other companies which are profiting off of the corpse of Sears. The individual didn’t need to buy up 100 percent of Sears stock to take control of it, they only needed 51 percent. Then once they were in complete control, with only 51 percent of the votes, they started to sell off Sears real estate to their other companies. They intentionally setup a system where once the individual stores stopped being profitable, they’d sell the land out from under them and close the store. There was nothing that the other 49 percent of the stockholders could do about it.

So not only are the other stockholders effectively being stolen from, but there are many employees whose lives are ruined because of greedy decisions make by someone who shouldn’t have complete control, but does. Is that really healthy for society to operate like that?

For another scenario, imagine a country, state or voting district where one large portion of the population never wins. Imagine two parties, one which gets 51 percent of the vote every time, and one which gets 49 percent of the vote, every time. If voting for representatives, that gives the 51 percent 100 percent of the representatives, over and over again. How long will 49 percent of the population stand for that? What will they do when they’ve had enough? How will they fight back?

Now in reality, I can’t think of a specific example of it being so constantly close like that, and there are lots of places where the winds of fortune change, but for lots of people still it feels like their vote doesn’t matter, because their “side” never wins. It’s hard to feel like an equal member of society when your voice is never heard. When there is never a need for compromise.

It’s important for people to feel like they’re participating in society and that their vote counts. Years ago, I had a conversation with a co-worker who had just immigrated from China. We were discussing how odd it was for him to see people not constantly trying to cheat the system. My response was how to some degree, we all created the system and we don’t want to cheat the thing we created. If there is something wrong, we don’t cheat our way around it, we work to get the wrong thing changed. Bad law, corrupt police, anything. We are a participating member of society.

 

Is there something that can be done to prevent a tyranny of the majority? And a way to help people know that their vote counts? I believe that there is.

I’ve posted before a voting solution which will cure all voting ills. But many of the people that I’ve talked to about it, find it to be too much of a burden on the voter. As a first step I think that we should move to a multi-victor voting district solution. At the Federal level in the United States, this would work by passing a law which states: The entire state is one voting district. The number of seats in the House will be proportioned out to the different parties based off of the number of votes they received. If the state has more than 15 possible seats, then the state shall be divided up into voting districts of equal population with each district containing no less than 8 seats, and no more than 15 seats.

Imagine a state where 50 percent of the people vote Democrat, 40 percent vote Republican and 10 percent vote Libertarian. Given that the Libertarians are never concentrated enough to ever win a seat in the current system, those voters feel that their voice is never heard. The Democrats and Republicans carve up the state to ensure that most seats are safe, and maybe one or two are contested over. But if the whole state was one voting district, with 10 seats, then Democrats would get 5 seats, Republicans 4 and Libertarians 1. Now there is a chance for third parties to form. In addition, more people will feel more motivated to vote, because it could mean the difference between their party receiving 4 or 5 seats. Whether your vote is part of the majority or the minority, your vote is never thrown away.

What about the US Senate? Same thing. But instead of voting for Senators in different elections, a state would vote for both of their Senators in the same election. Should a party get 34 percent of the vote, they win one Senate seat. The party with the most remaining votes gets the 2nd seat. Should a party win 67 percent of the vote, they get both Senate seats. I suspect though, the vast majority of the time, the two seats will be divided between the two parties with the greatest number of votes.

What about a company where 51 percent of the stockholders are not acting in the best interest of the company? Make it illegal for 51 – 99 percent of the stocks in a company to be owned by a single individual. An individual can own 100 percent of the stocks, or a minority of stocks, but not a majority. Yes, I realize that’s against the spirit of “I should be able to do whatever I want with my money”, but I don’t give much weight to that point of view. Peoples livelihoods are involved here. Leadership decisions should be being made with the interest of the organization in mind; not a takeover. In addition, if money is so precious, what about the money of the remaining stockholders. They didn’t purchase the stock for it to become worthless. Or those shareholders may even be employees who don’t want to lose a job for no good reason. A corporation is a powerful force, that’s why Adam Smith wrote about them centuries ago. Corporations need to follow rules for the betterment of society.

Tyranny of the majority is a real thing, and different systems of democracy have checks and balances against them. But the current checks and balances currently in the United States, may not be sufficient. To prevent Civil War, or to encourage greater civil participation, or to prevent pillaging of other peoples assets, we the people need to make some changes for the betterment of all of us.

Captain Marvel is Better than Wonder Woman

April 22, 2019 Leave a comment

The movie Captain Marvel (2019) is better than the movie Wonder Woman (2017). For some reason everyone can’t help but compare the two and when I compare the two, Captain Marvel comes out as the better movie. It’s because the protagonist overcame something in one but not in the other.
This isn’t to say that Wonder Woman isn’t an enjoyable watch, it is; but when watching it you never get the sense that Diana is going to do anything but succeed at everything she tries to do. At the end of the movie they even spell it out: she’s the god killer, the gift given to the Amazons to defeat Ares; she was preordained to succeed. Captain Marvel doesn’t have that sense at all. Vers (the name of Captain Marvel for most of the movie) does fail. She can’t defeat her commanding officer is a joust, she gets captured in an ambush, she can’t hunt down the Skrull’s on her own, the Skrulls can hurt her, etc.
In Wonder Woman you never get the sense that Wonder Woman is ever in danger. Diana throws herself into danger and succeeds stunningly without ever getting scratched over and over. Does she even ever get knocked down? Captain Marvel certainly gets knocked down. The movie has montages of her getting knocked down. The movie is a story of overcoming adversity. Which then makes the montage of her getting back up again, all the more powerful.
I don’t think that Wonder Woman has any character development. Yes, she learns about the larger world, but she doesn’t seem to be any different at the end of the movie than when she was the little girl doing impossible things. Captain Marvel finds her humanity in her movie. She goes from being a space soldier to someone with friends, who ends up betraying all that she knew for doing the right thing. She also overcomes the restrictions that she had been living under. I find it something which can be related to and inspiring, than Wonder Womans’ invincible person who can’t be beat, story.
Wonder Woman’s fish-out-of-water scenes are way better than Captain Marvel’s. They’re funnier, they make more sense, and are overall better. The way it’s played in Captain Marvel feels like the humor is forced and her actions don’t make a lot of sense. While I get that the Kree don’t have a strict Federation like Prime Directive, Vers walking around a planet, that she should know doesn’t know about the outside galaxy, asking for “Star Command” (or whatever it is in the movie) is odd. She barely even tries to go covert, which is odd. She’s a lone soldier, in a foreign land, she shouldn’t be sticking out. Yes, some bumbling about might make for humor, but it didn’t here.
The plot twists (or reveals) in Captain Marvel are better than those in Wonder Woman. In Wonder Woman they’re more on the nose, spelled out, more “shocking”, but what makes them shocking is that they’re oddly inconsistent with the rest of the movie. Particularly the who-Ares-actually-is reveal. While surprising, you then can’t help but think “If he was Ares all along, why did he help get Diana to the place which would stop his final plan? And why then did he show up to confront the one person that could kill him? And why does he tell that person that she’s the one that can kill him?” You went from a sneaky villain to a bumbling one. The Skrulls-are-oppressed twist takes longer to play out, isn’t so black and white, you kind of don’t buy it and are waiting for a double twist to happen, which then never comes.
Captain Marvel wins out as the better movie. I found the characters arc’s better, the story was better, the music was more thematically consistent, it was just better. Both movies are enjoyable to watch but one has a sense of danger where the other one did not; and one has a protagonist who learns how to stand back up, while the other doesn’t know what it’s like to be knocked down.

Categories: Entertainment

Best Possible Opening Scene for Black Panther

September 6, 2016 Leave a comment

I know that it’s still more than two years until Marvel releases their first Black Panther movie, but I already have in my mind what the best possible opening scene would be. It should mimic the opening scene of Captain America: The Winter Soldier. Opening scene should be sunrise in Wakanda with Sam Wilson running. A faster runner passes him on his left and you hear Steve Rogers say “On your left.” Next shot, Sam Wilson is running a long and a faster runner passes him on his left and you hear Black Panther say “On your left.” I think it would be funny.

Now its possible that Doctor Strange, Guardians of the Galaxy 2, or Thor Ragnarok are going to move Steve Rogers and Sam Wilson from Wakanda, but I doubt it. Captain America: Civil War left them in Wakanda, so it would make sense to see them in the Black Panther movie. Probably not has vital characters, but as cameos. Have them in an earlier scene, explain that they’re off going to be doing something else (rendezvous with Sharon Carter perhaps), and have it be that. I’ll be rather bummed if they don’t make an appearance at all.

Categories: Entertainment

Comic Movies Should Use Codenames More

May 12, 2016 Leave a comment

Something which bothers me with a lot of comic book based movies is that they don’t use the characters codename more. A lot of characters will have two names, their civilian name, and their code name. For example, Clark Kent is Superman. It seems like for the past 15 years or so, the code name is hardly ever mentioned. I think that lots of the movie going public, they wouldn’t even know a character’s civilian name, yet that’s how they’re referenced for most of the movie.

To me, what movie writers should do is to always have the characters be referred to by their code name when they’re on a mission. For example, in Star Wars, when the pilots are flying, they always refer to each other via code names (red two, gold leader, etc). The idea being that you don’t want the enemy to learn your actual names, should they be able to overhear your radio chatter. Comic book based movies need to do the same. When Steve Rogers and Natasha Romanoff are on a strike mission, they should always refer to each other as Captain America and Black Widow. When Black Widow and Captain America are back at base, chilling out, they can refer to each other as Natasha and Steve. It certainly would give a purpose to having these code names in the first place.

Categories: Entertainment

What Captain America: Civil War Is Missing

May 10, 2016 1 comment

I loved Captain America: Civil War. It certainly draws one in, and makes one feel what the characters are feeling. And while there are some things which I would have done differently if I were directing the movie (and those opinions are my own) this is a list small things which would have added to what is already there.

The First Action Scene Needs To Be Tied In With The Rest Of The Movie

While the explosion at the end of the sting operation in Lagos does get the ball rolling for the rest of the movie, the scene itself is pretty independent of the rest of the plot. It’s a fun and exciting scene, but I think it was missing something; it was missing Zemo. In Winter Soldier where they’re rescuing hostages from the Lumarian Star, who was on the boat, and what it was doing in the first place, became significant to the overall plot. But in Civil War, the Biohazardous material and Rumlow trying to get it, had nothing to do with the rest of the story at all. I think it would have been great if there was some reference to Zemo sending Rumlow/Crossbones out on these “missions”, not to accomplish whatever they were trying to do, but to get the Avengers to commit some sort of collateral damage.

Each Side Needed One More Argument

While most people praise Civil War for not bogging down the movie with a dialogue and a debate between the two sides, I think that each side needed one more point to really round out their argument.

  • Steve Rogers should have asked “What would we have done differently with an oversight committee?” Until the end of Winter Soldier the Avengers did have an oversight committee in the World Security Council. All the good that did, given that they almost launched Hydra controlled Helicarriers into the air, and ordered a Nuclear missile to blow up New York. The only ‘mistake’ the Avengers made was trying to interface with Loki’s Scepter which resulted in Ultron. And Tony Stark intentionally didn’t tell the rest of the team that he was doing that, so he certainly wouldn’t have told an oversight committee.
  • Tony Stark should have mentioned more of the legal complications that he was having. He does mention the issue he was having with housing Wanda in the US, and there is a TV playing in the background where someone asks “By what authority were the Avengers in Nigeria in the first place?” I think this should have been given one more sentence of air time. Tony should have said that by not even having quasi legal status, they were running into issues with getting countries to prosecute and detain the bad guys that they captured. Or that people who died while fighting the Avengers don’t become homicide cases. I’m pretty sure that lots of countries wouldn’t like the idea of a rich, white man sending his private army into their countries to do whatever they felt like doing

Zemo Needed To Be Doing Something Which Needed To Be Stopped

I think that lots of people will feel a bit of a let down from the end of the movie, but will struggle with why they’re feeling that way. My thought is that people will be feeling “Shouldn’t that climax have been more climactic?” Don’t get me wrong, the final conflict between Iron Man and Captain America was given great motivation and passion. I’m talking more about Zemo. The second act airport battle happened because Captain America needed to get to Siberia ASAP, to stop Zemo from getting his hands onto something very dangerous. But when Captain America finally gets to Zemo, Zemo says (and this is paraphrasing) “I wasn’t going after the dangerous thing, I just wanted to pick up this VHS.” Once your brain processes the fact that the last step in Zemo’s plot didn’t really need to be stopped, it’s a letdown. Zemo could have been getting a hold of material in hopes that it would tear the Avengers apart, in addition to getting a hold of another weapon he could use to perhaps kill off one or two of them.

Conclusion

So there you have it. A list of things which certainly don’t require big changes to Captain America: Civil War, but if where done would have made this great movie, even better.

Categories: Entertainment

How Rey is a Mary Sue

April 10, 2016 Leave a comment

Ever since Star Wars: The Force Awakens has been released there has been lots of discussion on the internet on the Mary Sue-ness of the character Rey. I will sum up all of the arguments I’ve seen here with my thoughts on them. Note: Episode VIII has yet to be named, let alone released; so this is my thoughts consisting of just The Force Awakens.(While there is no official definition of a Mary Sue you can get the rough working definition at http://tvtropes.org/pmwiki/pmwiki.php/Main/MarySue)

  1. Rey beats up the two men who were sent to kidnap her.
    1. This doesn’t come off as a Mary Sue to me. While I was slightly rolling my eyes at it when I first saw The Force Awakens, I’m more okay with it the more I’ve had to think about it. You have two guys who are caught of guard by the resistance their target was able to put up. So far, not a Mary Sue.
  2. Rey flies the Millennium Falcon well enough to fight off two Tie fighters.
    1. Given that she’s a junk collector and there’s no established precedent for her piloting abilities, solid Mary Sue. The only imperfection in the scene is that she had Finn go to the bottom turret instead of the top, but that just created more opportunity to pull off more unlikely maneuvers. Very much Mary Sue writing by the writers.
  3. Rey fixes issues with the Millennium Falcon on the fly.
    1. It’s been established that she’s a scavenger, so also being a mechanic isn’t too far fetched. At least a bailing wire and duct tape type of mechanic. It’s not out of character, not a Mary Sue.
  4. Rey has all of the impressive stats of the Millennium Falcon memorized.
    1. Very Mary Sue. She’s being a fan for the fans.
  5. Rey releases the Rathtar’s aboard Han Solo’s ship.
    1. This is generally pointed out how Rey made a mistake and therefore isn’t a Mary Sue. While it was a mistake, it resulted in getting rid of the gangsters they were trying to get away from, and none of the hero’s were harmed. But it wasn’t an expression of out of character ability, so I’m going with neutral. Neither Mary Sue or not.
  6. Ren captures Rey on Takodana.
    1. This wouldn’t have happened with a Mary Sue. So non-Mary Sue.
  7. Rey resists Ren’s invasion of her mind.
    1. I’m inclined that this should be a Mary Sue, given that Kylo Ren has been presented at being very good at memory reading, but there’s enough precedent for natural Force users to be different in certain ways that I’m going to let it go. So non-Mary Sue.
  8. Rey mind tricks the storm trooper guarding her, into letting her go.
    1. Solid Mary Sue. She has know idea that a Force user could even do such a thing, let alone doing it without ever having consciously used the Force before. Besides, wouldn’t it have been absolutely horrible if Finn actually had to have saved her? Can’t have that.
  9. Rey calls the lightsaber to her.
    1. Mary Sue. Ren is calling it to him at the same time and Rey get’s it.
  10. Rey’s lightsaber battle with Ren is a draw.
    1. Mary Sue. I don’t care if she’s a fighter, or that Ren’s hurt. Kylo Ren shouldn’t have been hit by Chewbacca’s shot anyway. It’s just that without it, even the writers couldn’t have justified a draw, so they did something very convenient for Rey, so it wouldn’t be so absurd for Rey to do as well as she did against Ren, using a weapon she’s never picked up before. So given that the existing premise of Ren’s abilities had to be bent to even get to that point, Mary Sue.
  11. Rey is sent to find Luke Skywalker.
    1. Given what we know from The Force Awakens, also a Mary Sue. Why would Leia send a newbie stranger to go find her brother that she’s been looking for for years. Oh I know, because it’s really convenient for the awesomeness of Rey.

And those are my thoughts. Rey is a Mary Sue. The biggest reason for why I see that she shouldn’t be is “She’s so cool, I don’t want her to be.” But that’s the point. She’s too cool.

 

Categories: Entertainment