Unclearance in mutual exclusion example - process

I have read several examples about mutual exclusions, and I can understand the run of most of them except the following example handed to me:
boolean[] flag = new boolean[2];
one while-condition is depending on the flag[n] state of the other process.
So in order to for example have P1 heading into it's critical section both flag[0] and flag[1] need to be set true.
According to my interpertation the entire run will have to look like this:
P1 - > flag[1] = true
while(flag[0]) // flag[0] is still state-undeclared
P2 -> flag[0] = true // so P0 must set it true(?)
critic1();
while(flag[1])
critic2();
Though this can't be correct since with flag[0] and flag[1] set to true both processes pass the while(flag[n]) condition and a race-condition could still occur. What am I misunderstanding?

The declaration and definition
boolean[] flag = new boolean[2];
looks like java, and in java the boolean array is filled with false as default values.
So in order to for example have P1 heading into it's critical section
both flag[0] and flag[1] need to be set true.
No that is not the case, for P1 to be heading into the Critical Section, only thing is that following statement of P0 must not be executed before P1 enters the Critical Section.
flag[0] = true;
and since by default flag[0] = false, the loop condition while(flag[0]) will be false and P1 will enter the critical section.
If processes P0 and P1 are scheduled in such a way that the following statements are executed for both processes before the corresponding next statement:
flag[0] = true; and flag[1] = true;
In such case deadlock will occur.

Related

PedSelectOutPut routing pedestrians inconsistently

I am simulating the passenger changeover process in metros using the Anylogic Pedestrian Library.
When passengers enter the vehicle, a seat is assigned to them from the seats available near the door (within a given distance) they entered the vehicle through, using a function called lookForSeat. If there is no more free seat available, their boolean parameter wantToSit is set to false and they will stay standing.
The parameter wantToSit is predefined for the Passenger Agent, with default value randomtrue(0.8). But even if I set it to default value = 1, I get the same error.
Then, passengers are separated using a PedSelectOutput block:
Condition 1: if ped.WantToSit = true --> they are sent to their
assigned seat coordinates (PointNode 'seatPoint', null by default)
Condition 2: true (thus, ped.WantToSit = false) --> they stay in the
standing area in the vehicle, no assigned seatPoint necessary in this case.
Now, it works pretty well, but when the majority of the seats is already occupied, suddenly the PedSelectOutput block directs a passenger with ped.wantToSit to its seating point, which gives null and I get the NullPointerException error.
Attached you find the function, the settings of PedSelectOutput and the log from the command.
As it can be seen, the PedSelectOutput sends the passenger through exit 1 (which gives the error due to calling the coordinates of a "null"), despite ped.wantToSit = false.
Any ideas, what is going wrong? For me it really looks like the function is working properly - I have been changing it the whole day until I realized that something in the PedSelectOutput block goes wrong.
Thank you in advance!
Pic 1: pedSelectOutput block and the command with the log
Pic 2: the function lookForSeat assigning the seats from the seat Collection
The problem here is a subtle one, which has caused me many hours of debugging as well. What you need to understand is that the on exit code is only executed once the agent already has a path to which it is going to exit. i.e. the selectOutput and subsequent blocks are already evaluated and only once it is determined that the agent can move to the next block then the on exit code is called. But the agent will continue on its chosen path that has been determined before the on exit code has been executed.
See the small example below:
I have a pedestrian with a variable that is true by default and a select output that checks this value
If I ran the model all pedestrians exit at the top option, as expected
If I change the variable to false on the On Exit code I might expect that all pedestrians will now exit at the second option
But they don't there is no change....
If I add the code to the on enter code then it does..

How to check if a "Send Query" is over?

I need to check if my res from dbSendQuery() is over.
My code is like this:
db <- dbConnect(drv=SQLite(),flags=SQLITE_RW,dbname="db.sqlite",synchronous = "off")
dbBegin(db)
res <- dbSendQuery(db,"Update Operation SET Name = 'teste' where Id = 1")
if("my SendQuery is over"){
dbClearResult(res)
dbCommit(db)
dbDisconnect(db)
}
I need to know when it is over to send this to commit and then disconnect.
UPDATE 1
Im my sistem, for this example above can happen with more than 1 users simultaneous.
Then, when the first connection in db is over, i need to finish him requisition and provide to the other connection the possibility to write your query.
dbSendQuery() always awaits completion. You can double-check by calling dbGetRowsAffected(res) .
For SQL statements that are run for the side effect and do not return a value, dbSendStatement() is preferred.
The synchronous = "off" argument to dbConnect() is a misnomer, this defines when and how the data is written to disk; no multi-threading is involved here.

synchronization between 2 applications pooling a SQL table

I have 2 instances of a VB.NET application each running on their own dedicated servers. The said application runs a While true loop with a 5s sleep on IDLE (IDLE is when the Table doesn't have any ProcessQuery to be treated). On each iteration, the application questions a table in the SQL Database to know if there is anything it could process.
The problem is that i sometimes encounter the problem where both of the instances are "taking" the same ProcessQuery.
I'm using EntityFramework6. I have looked into EntityState but i don't think it does exactly what i'm trying to accomplish.
I was wondering what would be my solution to have perfect parallel instances. It's not impossible at some point i have 12 instances running on 12 machines.
Thanks!
Dim conn As New Info_IndusEntities()
Dim DemandeWilma As WilmaDemandes = conn.WilmaDemandes.Where(Function(x) x.Site = 'LONDON' AndAlso x.Statut = 'toProcess').OrderBy(Function(x) x.RequestDate).FirstOrDefault
If Not IsNothing(DemandeWilma) Then
DemandeWilma.Statut = Statuts.EnTraitement.ToString
DemandeWilma.ServerName = Environment.MachineName
DemandeWilma.ProcessDate = DateTime.Now
conn.SaveChanges()
Return DemandeWilma
end if
UPDATE (21/06/19)
I found an article that I find interesting.
I started by adding a column to my Table :
UPDATED (21/06/19)
I then refreshed my model and changed the Concurrency Check property of RowVersion column in my ORM :
When I tested the update, here's the log of EF6 :
UPDATE [dbo].[WilmaDemandes] SET [Statut] = #0, [ServerName] = #1,
[DateDebut] = #2 WHERE (([ID] = #3) AND ([RowVersion] = #4)) SELECT
[RowVersion] FROM [dbo].[WilmaDemandes] WHERE ##ROWCOUNT > 0 AND [ID]
= #3
-- #0: 'EnTraitement' (Type = String, Size = 20)
-- #1: 'TRB5995' (Type = String, Size = 20)
-- #2: '2019-06-25 7:31:01 AM' (Type = DateTime2)
-- #3: '124373' (Type = Int32)
-- #4: 'System.Byte[]' (Type = Binary, Size = 8)
-- Executing at 2019-06-25 7:31:24 AM -04:00
-- Completed in 95 ms with result: SqlDataReader
Closed connection at 2019-06-25 7:31:24 AM -04:00
Exception thrown:
'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' in
EntityFramework.dll
UPDATED (25/06/19)
The problems, as explained in this post, starts when you are using DB-First instead of Code-First. Your property will get overwritten silently as soon as you update the model. Some people back then coded a console app workaround that they run on pre-build. I'm not sure i'm quite ready to take this solution as final solution.
Interesting tutorial on how to test optimistic concurrency and ways to resolve such an exception.
Add an "owner" column to your queue table
Your application updates one record (TOP 1) and sets the owner value to their identifier (WHERE Owner IS NULL)
Now your application goes back and reads their owned rows and processes them
It's a simple pattern and it works great. If any processes happen to take ownership 'simultaneously', only one will actually get the reservation.
I'm not very good at LINQ so here's a brute force method, multiline for clarity:
// First try reserving a row
conn.Database.ExecuteSqlCommand(
"WITH UpdateTop1 AS
(SELECT TOP 1 * FROM WilmaDemandes
WHERE Owner IS NULL
AND Site = 'LONDON'
ORDER BY RequestDate)
UPDATE UpdateTop1 SET Owner='ThisApplication'"
);
// See if we got one
Dim DemandeWilma As WilmaDemandes =
conn.WilmaDemandes.
Where(x => x.Owner=='ThisApplication').FirstOrDefault
// If we got a row, process it. Otherwise Idle and repeat
There's also no reason that you must reserve one row. You could reserve all the free rows and work your way through them. Meanwhile other processes will pick up any subsequently arriving rows
Personally I would refactor your status column and make it NULL for new records ready to be processed, otherwise it's the worker ID that has reserved it.
It also helps to add things like timestamp columns to record when the row was reserved etc.

What's the equivalent of moment-yielding (from Tornado) in Twisted?

Part of the implementation of inlineCallbacks is this:
if isinstance(result, Deferred):
# a deferred was yielded, get the result.
def gotResult(r):
if waiting[0]:
waiting[0] = False
waiting[1] = r
else:
_inlineCallbacks(r, g, deferred)
result.addBoth(gotResult)
if waiting[0]:
# Haven't called back yet, set flag so that we get reinvoked
# and return from the loop
waiting[0] = False
return deferred
result = waiting[1]
# Reset waiting to initial values for next loop. gotResult uses
# waiting, but this isn't a problem because gotResult is only
# executed once, and if it hasn't been executed yet, the return
# branch above would have been taken.
waiting[0] = True
waiting[1] = None
As it is shown, if in am inlineCallbacks-decorated function I make a call like this:
#inlineCallbacks
def myfunction(a, b):
c = callsomething(a)
yield twisted.internet.defer.succeed(None)
print callsomething2(b, c)
This yield will get back to the function immediately (this means: it won't be re-scheduled but immediately continue from the yield). This contrasts with Tornado's tornado.gen.moment (which isn't more than an already-resolved Future with a result of None), which makes the yielder re-schedule itself, regardless the future being already resolved or not.
How can I run a behavior like the one Tornado does when yielding a dummy future like moment?
The equivalent might be something like a yielding a Deferred that doesn't fire until "soon". reactor.callLater(0, ...) is generally accepted to create a timed event that doesn't run now but will run pretty soon. You can easily get a Deferred that fires based on this using twisted.internet.task.deferLater(reactor, 0, lambda: None).
You may want to look at alternate scheduling tools instead, though (in both Twisted and Tornado). This kind of re-scheduling trick generally only works in small, simple applications. Its effectiveness diminishes the more tasks concurrently employ it.
Consider whether something like twisted.internet.task.cooperate might provide a better solution instead.

NamingEnumeration hasMoreElements method takes a lot of time when returning false for LDAP

I am trying to search a LDAP server(Active Directory). When I parse the search results, the hasMoreElements method of NamingEnumeration takes around 15-20 seconds to execute when it returns false. It is not the case when it is returning true. Is there a way to solve this issue?
Code:
SearchControls ctrl = new SearchControls();
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectClass=user("uid"="abc"))";
NamingEnumeration ne = dirContext.search("ldap://abc:389/dc=abc,dc=xy", searchFilter,ctrl);
if (ne != null) {
while (ne.hasMoreElements()) {
//parse results
}
The NamingEnumeration does some cleanup when calling hasMoreElements() the last time. It also checks if there are additional referrals is the context-property Context.REFERRAL is set to "follow". In one case in our software this caused exactly the behaviour as described: The last call to hasMoreElements() (or to hasMore() or calling next() more often than allowed) caused up to 40 seconds as referrals are searched in the LDAP context. The solution is to not set Context.REFERRAL to "follow".
AD has a default limit of number of objects it returns in an LDAP query. I think it is in the 1000 object range.
If you hit 1001, you get 1000 returned, then an error, so I could see this being the case.
Count how many objects you get back in a test, and betcha you beat 1000 and then fail.