How can i make my code "save against concurrent invocations" when using "NSSortConcurrent" in sortedArrayWithOptions:usingComparator? - objective-c

Im trying to sort an Array of NSDates using the sortedArrayWithOptions:usingComparator: - method od NSArray. So far all is very well and my code works as expected.
However, seeing that i can specify options for the method to use, i went into the docs and tried to figure out what they mean.
Theres NSSortStable, of course: Objects that have the same Value should be returned in the order they existed in before the sort. Thats easy enough, i guess.
But im somewhat stumped as to what NSSortConcurrent means. This is what the docs say:
Specifies that the Block sort operation should be concurrent.
This option is a hint and may be ignored by the implementation under some circumstances;
the code of the Block must be safe against concurrent invocation.
Available in Mac OS X v10.6 and later.
So i understand that i can allow the use of multiple threads for the sorting operation? thats great. In this case, is "save against concurrent invocations" just fancy talk for "thread-safe"? And if it isnt, what does it mean? Im sorry for this rather stupid question, but im not a native english speaker. Thanks.

Never mind, i figured ot out. NSSortConcurrent will indeed allow the sorting operation to use multiple threads, and thus the only rewuirement is for the sorting block to be thread-safe. As long as youre not touching any data that is located outside the block (so dont use __block-variables) you should be fine.

Related

Having trouble making my VI work as a Sub VI

I am having trouble getting the terminals to pass any data to what they are connected to because the controls they connect to are in a while loop. My frustration level is high since I would have already had this done if I wrote it in C.
First, let me say this might get a little long so if you don't want to read it, then don't. Here goes. I have watched a couple of tutorials, read a lot, and even tried a few things out in code. I get why this can't be done directly in a while loop. Having said that, it seems that I have no choice but to use while loop(s) in my VI.
My VI is loosely based on Queued Message Handler in the Templates section of creating a new VI. I have 2 things that must take place. One - I have created a TCP client where I constantly send messages to get status from the equipment I am communicating with. This is a timed event and must be handled in a while loop so I can maintain the connection to the server. I am not doing the Open, Send, Close, Reopen, Send, Close, etc. type of message handling. Too inefficient. This is the lower half of the example template.
Second - On occasion the user will press a button on the front panel which creates a message that is sent to the equipment to make it do something. And this, it would seem, needs to be in a while loop also, hence my problem. Some/most of the controls exist with the event structure. This is the top half of the example template.
I actually have this working as a front panel, but every thing is in just one while loop and I cannot get the terminals to work. Here is where my confusion comes in, if I am passing something to the while loop, I only get its value once and if it changes, you don't get that change, and if you are passing the data out of the while loop, you only get it when the loop ends. These two things are really baffling me. How can pass data that changes while using a while loop, because I have to, but the while loop breaks using the terminals. Seems circular. The TCP communications cannot stop, and I cannot find an example of how to do this using my friend Google. Am I the only person on this planet that needs to do this? Doubt it.
Not going to show my code, as this in not a code problem. It is an understanding how LabView does things vs. how you would just write the code in C using some library. And also just being unfamiliar with all the things you can do in LabView, not to mention how things are different. I don't know what I don't know, but I can learn.
I want to be able to give the VI I have created to any user and let them use it to control my equipment. If they just want to run it as a front panel, or if they want to use it as a Sub VI that is OK too. I just need to be able to make the terminals actually pass data when used that way.
Thanks, I did order a book on LabView today, but I won't get it soon. I really need to put this problem to bed.
Cannot help that much without seeing the code. But I can try to give you a little bit of an idea of what is going on.
Dataflow is an important concept to understand in LabVIEW. elements (VIs, loops, etc.) will not start until all of their inputs (ie. terminals) have been received or set by something called before, and then they only take their inputs once. If your terminal is outside the loop, then the loop can only read it's starting value. (See "Infinite Loops" on this page). A simple way of solving this would be to put the terminal inside of the loop rather than outside, so it is then read on every iteration of the loop.
As for passing values outside of the loop, there are a number of methods for this. Again, because of dataflow, you will not usually be able to access the value of something inside the loop until the loop finishes executing. However, there are a number of ways to read those values in a different loop. Local or global variables would be the simplest way, but they are not recommended by NI. The proper way of handling this is using something on the synchronization pallet. More info on the options can be found here.
Seeing as you are basing something on the Queued Message Handler, a queue might be a good way to start. LabVIEW has built in examples of code to show you how to use these functions.
Loop synchronization and asynchronous programming are fundamental concepts for writing LabVIEW code. If these are not concepts you are familiar with, I would say that you will gain a lot from showing others your actual code and having people help you with the issues. If you are concerned about sharing something proprietary, try making a simple example and posting that code instead to understand the concepts better.
Event structure to react to evr8and functional global to pass data out.
Suggest pasting block diagram.

Mobx Autorun running too often / need it to skip in some cases / run only after finished

I know its not best practice but its the most performant solution I have found so far. It monitors an object, and transforms that object in the autorun.
This setup is working excellently for small data sets, but when there are a lot of changes, it gets stuck in the "100 cycles and didn't settle" error.
I was wondering if there was some way to get it to iterate just once / collate all changes and apply them in one hit.
I have tried a number of solutions / workarounds that involve timers, deep object comparison (ie don't run if it hasn't changed) etc, but they either disable the autorun or lead to extremely bad performance.
I guess in summary:
Is there some way to make autorun not execute changes on the same frame?
Is there a better solution for autorun to watch every observable in an object?
Is there a way to limit autorun?
Is there a better solution?
It is hard to say anything useful without some minimal code example of what you are doing. But it sounds like you are reading and modifying the same data in the autorun, which introduces cycles. Consider using reaction which allows you to better separate what data you want to listen react, versus the action you want to take once a change occurs

Modelica - how to implement a constructor for a record

What is the best way to implement a constructor for a record? It seems like a function should be able to return a record object in the instantiation of the record in some later model higher up the tree, but I can't get that to work. For now I just use a bunch of parameters at the top of the record that populate the variables stored in the record, but it seems like that will only work in simple cases.
Can anyone shed a little light? Perhaps I shouldn't be using a record but a model. Also does anyone know how the PDE functionality is coming? The book only says that it is coming, but I have seen some other things around.
I don't seem to have the clout to add tags (which makes sense, since my "reputation" is lower than yours) so sorry about that. I thought I had actually added one at one point, but perhaps I am mistaken.
I think you need to be clear what you mean by constructor since it has a very specific meaning in Modelica. If I understand your question correctly, it sounds like what you want to do is create an instance of a record that has some fields that are specified in the constructor arguments and from those arguments a bunch of other fields in the record are computed. Is that correct?
If so, there is a mechanism to do this. You mention "the book" but it isn't clear which one you mean. If it is mine, it definitely has no mention of these so called "record constructors" because it is too old. I do not know if Peter Fritzson's book mentions them either. However, they do exist and are documented in Section 12.6 of the Modelica 3.2 specification.
As for PDEs, there has been work into this kind of thing but nothing has really been done within the design group on this topic. I would add that if you want to solve either elliptical or parabolic PDEs on regular grids, this isn't too hard even with the current language. The only real drawback is that most tools probably don't handle sparsity very efficiently. Irregular grids would also be possible, but then you get into complicated basis functions. Finally, hyperbolic PDEs are, in my opinion, quite tricky (in any environment) due to the implicit physical constraints between time and space which are difficult to express (i.e. the CFL condition).
I hope that answers your questions so far.
I can only comment on your question regarding the book of Peter Fritzson. He confirmed that he's working on an update and he hopes to get it ready 'in the course of 2011'.
Original post here:
http://openmodelica.org/index.php/forum/topic?id=50
And thanks for initiating the modelica tag, I might be useful in the near future for me too... :-)
regards,
Roel

Can Parallel.ForEach be used safely with CloudTableQuery

I have a reasonable number of records in an Azure Table that I'm attempting to do some one time data encryption on. I thought that I could speed things up by using a Parallel.ForEach. Also because there are more than 1K records and I don't want to mess around with continuation tokens myself I'm using a CloudTableQuery to get my enumerator.
My problem is that some of my records have been double encrypted and I realised that I'm not sure how thread safe the enumerator returned by CloudTableQuery.Execute() is. Has anyone else out there had any experience with this combination?
I would be willing to bet the answer to Execute returning a thread-safe IEnumerator implementation is highly unlikely. That said, this sounds like yet another case for the producer-consumer pattern.
In your specific scenario I would have the original thread that called Execute read the results off sequentially and stuff them into a BlockingCollection<T>. Before you start doing that though, you want to start a separate Task that will control the consumption of those items using Parallel::ForEach. Now, you will probably also want to look into using the GetConsumingPartitioner method of the ParallelExtensions library in order to be most efficient since the default partitioner will create more overhead than you want in this case. You can read more about this from this blog post.
An added bonus of using BlockingCollection<T> over a raw ConcurrentQueueu<T> is that it offers the ability to set bounds which can help block the producer from adding more items to the collection than the consumers can keep up with. You will of course need to do some performance testing to find the sweet spot for your application.
Despite my best efforts I've been unable to replicate my original problem. My conclusion is therefore that it is perfectly OK to use Parallel.ForEach loops with CloudTableQuery.Execute().

What techniques are available for memory optimizing in 8051 assembly language?

I need to optimize code to get room for some new code. I do not have the space for all the changes. I can not use code bank switching (80c31 with 64k).
You haven't really given a lot to go on here, but there are two main levels of optimizations you can consider:
Micro-Optimizations:
eg. XOR A instead of MOV A,0
Adam has covered some of these nicely earlier.
Macro-Optimizations:
Look at the structure of your program, the data structures and algorithms used, the tasks performed, and think VERY hard about how these could be rearranged or even removed. Are there whole chunks of code that actually aren't used? Is your code full of debug output statements that the user never sees? Are there functions specific to a single customer that you could leave out of a general release?
To get a good handle on that, you'll need to work out WHERE your memory is being used up. The Linker map is a good place to start with this. Macro-optimizations are where the BIG wins can be made.
As an aside, you could - seriously- try rewriting parts of your code with a good optimizing C compiler. You may be amazed at how tight the code can be. A true assembler hotshot may be able to improve on it, but it can easily be better than most coders. I used the IAR one about 20 years ago, and it blew my socks off.
With assembly language, you'll have to optimize by hand. Here are a few techniques:
Note: IANA8051P (I am not an 8501 programmer but I have done lots of assembly on other 8 bit chips).
Go through the code looking for any duplicated bits, no matter how small and make them functions.
Learn some of the more unusual instructions and see if you can use them to optimize, eg. A nice trick is to use XOR A to clear the accumulator instead of MOV A,0 - it saves a byte.
Another neat trick is if you call a function before returning, just jump to it eg, instead of:
CALL otherfunc
RET
Just do:
JMP otherfunc
Always make sure you are doing relative jumps and branches wherever possible, they use less memory than absolute jumps.
That's all I can think of off the top of my head for the moment.
Sorry I am coming to this late, but I once had exactly the same problem, and it became a repeated problem that kept coming back to me. In my case the project was a telephone, on an 8051 family processor, and I had totally maxed out the ROM (code) memory. It kept coming back to me because management kept requesting new features, so each new feature became a two step process. 1) Optimize old stuff to make room 2) Implement the new feature, using up the room I just made.
There are two approaches to optimization. Tactical and Strategical. Tactical optimizations save a few bytes at a time with a micro optimization idea. I think you need strategic optimizations which involve a more radical rethinking about how you are doing things.
Something I remember worked for me and could work for you;
Look at the essence of what your code has to do and try to distill out some really strong flexible primitive operations. Then rebuild your top level code so that it does nothing low level at all except call on the primitives. Ideally use a table based approach, your table contains stuff like; Input state, event, output state, primitives.... In other words when an event happens, look up a cell in the table for that event in the current state. That cell tells you what new state to change to (optionally) and what primitive(s) (if any) to execute. You might need multiple sets of states/events/tables/primitives for different layers/subsystems.
One of the many benefits of this approach is that you can think of it as building a custom language for your particular problem, in which you can very efficiently (i.e. with minimal extra code) create new functionality simply by modifying the table.
Sorry I am months late and you probably didn't have time to do something this radical anyway. For all I know you were already using a similar approach! But my answer might help someone else someday who knows.
In the whacked-out department, you could also consider compressing part of your code and only keeping some part that is actively used decompressed at any particular point in time. I have a hard time believing that the code required for the compress/decompress system would be small enough a portion of the tiny memory of the 8051 to make this worthwhile, but has worked wonders on slightly larger systems.
Yet another approach is to turn to a byte-code format or the kind of table-driven code that some state machine tools output -- having a machine understand what your app is doing and generating a completely incomprehensible implementation can be a great way to save room :)
Finally, if the code is indeed compiled in C, I would suggest compiling with a range of different options to see what happens. Also, I wrote a piece on compact C coding for the ESC back in 2001 that is still pretty current. See that text for other tricks for small machines.
1) Where possible save your variables in Idata not in xdata
2) Look at your Jmp statements – make use of SJmp and AJmp
I assume you know it won't fit because you wrote/complied and got the "out of memory" error. :) It appears the answers address your question pretty accurately; short of getting code examples.
I would, however, recommend a few additional thoughts;
Make sure all the code is really
being used -- code coverage test? An
unused sub is a big win -- this is a
tough step -- if you're the original
author, it may be easier -- (well, maybe) :)
Ensure the level of "verification"
and initialization -- sometimes we
have a tendency to be over zealous
in insuring we have initialized
variables/memory and sure enough
rightly so, how many times have we
been bitten by it. Not saying don't
initialize (duh), but if we're doing
a memory move, the destination
doesn't need to be zero'd first --
this dovetails with
1 --
Eval the new features -- can an
existing sub be be enhanced to cover
both functions or perhaps an
existing feature replaced?
Break up big code if a piece of the
big code can save creating a new
little code.
or perhaps there's an argument for hardware version 2.0 on the table now ... :)
regards
Besides the already mentioned (more or less) obvious optimizations, here is a really weird (and almost impossible to achieve) one: Code reuse. And with Code reuse I dont mean the normal reuse, but to a) reuse your code as data or b) to reuse your code as other code. Maybe you can create a lut (or whatever static data) that it can represented by the asm hex opcodes (here you have to look harvard vs von neumann architecture).
The other would reuse code by giving code a different meaning when you address it different. Here an example to make clear what I mean. If the bytes for your code look like this: AABCCCDDEEFFGGHH at address X where each letter stands for one opcode, imagine you would now jump to X+1. Maybe you get a complete different functionality where the now by space seperated bytes form the new opcodes: ABC CCD DE EF GH.
But beware: This is not only tricky to achieve (maybe its impossible), but its a horror to maintain. So if you are not a demo code (or something similiar exotic), I would recommend to use the already other mentioned ways to save mem.