How to create an atomic function in objective-c - objective-c

Is there a way to execute a whole objective-c function atomic?
As far as I know, using synchronized only protects a specific peace of code from being executed on multiple threads at the same time. But what I want is stop ALL other threads from doing ANYTHING, as long as I execute the function.

There is a wealth of info in the Threading Programming Guide. It specifically mentions to avoid synchronization (which is funny, cause you cant sometimes) but they offer some suggestions around the problem.
You will have serious problems with your design if you start running your software on multicore. It is a VERY expensive operation to stop all cores from running to run your bit of code. Mutexes, semaphores, run loop events, and atomic operations are the way to go.

Nope. Can't do that.
Or, well, you probably could if you dipped deep enough in the Mach APIs (on Mac OS X anyway).
But you shouldn't do that.
Why do you think you want to do that?

Related

Can I run a DLL in a separate thread?

I have a program I'm writing in vb.net that has ballooned into the most complicated thing I've ever written. Because of some complex math and image rendering that's happening constantly I've been delving into multithreading for the first time to improve overall performance. Things have honestly been running really smoothly, but we've just added more functionality that's causing me some trouble.
The new functionality comes from a pair of DLLs that are each processing a video stream from a USB camera and looking for moving objects. When I start my program I initiate the DLLs and they start viewing the cameras and processing the videos. I then periodically ping them to see if they have detected anything. This is how I start and stop them:
Declare Function StartLeftCameraDetection Lib "DetectorLibLeft.dll" Alias "StartCameraDetection" () As Integer
Declare Function StopLeftCameraDetection Lib "DetectorLibLeft.dll" Alias "StopCameraDetection" () As Integer
When I need to check if they've found any objects I use several functions like this:
Declare Function LeftDetectedObjectLeft Lib "DetectorLibLeft.dll" Alias "DetectedObjectLeft" () As Integer
All of that works really well. The problem is, I've started to notice some significant lag in my UI and I'm thinking it may be coming from the DLLs. Forgive my ignorance on this, but as I said I'm new to using multiple threads (and incorporating DLLs too if I'm honest). It seems to me that when I start a DLL it running it's background tasks on my main thread and just waiting for me to ping it for information. Is that the case? If so, is it possible to have the DLL running on a sperate thread so it doesn't affect my UI?
I've tried a few different things but I can't seem to address the lag. I moved the code that pings the DLL and processes whatever information it gets into a sperate thread, but that hasn't made any difference. I also tried calling StartLeftCameraDetection from a separate thread but that didn't seem to help either. Again, I'm guessing that's because the real culprit is the DLL itself running these constant background tasks on my main thread no what thread I actually call it's functions from.
Thanks in advance for any help you might be able to offer!
There's a lot to grok when it comes to threading, but I'll try to write a concise summary that hits the high points with enough details to cover what you need to know.
Multi-threaded synchronization is hard, so you should try to avoid it as much as possible. That doesn't mean avoiding multi-threading at all, it just means avoiding doing much more than sending a self-contained task off to a thread to run to completion and getting the results back when it's done.
Recognizing that multi-threaded synchronization is hard, it's even worse when it involves UI elements. So in .NET, the design is that any access to UI elements will only occur through one thread, typically referred to as the UI thread. If you are not explicitly writing multi-threaded code, then all of your code runs on the UI thread. And, while your code is running, the UI is blocked.
This also extends to external routines that you run through Declare Function. It's not really accurate to say that they are doing anything with "background tasks on the main thread", if they are doing anything with "background tasks" they are almost certainly implementing their own threading. More likely, they aren't doing any task breakdown at all, and all of their work is being done on whichever thread you use to call them---the UI thread if you're not doing anything else.
If the work being done in these routines is CPU-bound, then it would definitely make sense to push it off onto a worker thread. Based on your comments on what you already tried:
I moved the code that pings the DLL and processes whatever information it gets into a sperate thread, but that hasn't made any difference. I also tried calling StartLeftCameraDetection from a separate thread but that didn't seem to help either.
I think the most likely problem is that you're blocking in the UI thread waiting for a result from the background thread.
The best way to avoid this depends on exactly what the routines are doing and how they produce results. If they do some sort of extended process and return everything in function results, then I would suggest that using Await would work well. This will basically return control to the UI until the operation finishes, then resume whatever the rest of the calling routine was going to do.
Note that if you do this, the user will have full interaction with the UI, and you should react accordingly. You might need to disable some (or all) operations until it's done.
There are a lot of resources on Async and Await. I'd particularly recommend reading Stephen Cleary's blog articles to get a better understanding of how they work and potential pitfalls that you might encounter.

WebFlux locks. How?

I usually write imperative code on Java/Spring MVC, but now my team implement project on WebFlux. I tried to research the topic, but I can't find the answer to the question about locks.
It's normal when we have code that should always be executed by only one thread, or that has locks by some condition (for example, the code should not be executed concurrently for the same entity). These locks can be distributed, for example, through a Redis.
But how is this problem solved in Project Reactor? As far as I understand, it would be a bad idea to use a synchronized block, or ReentrantLock, because they will block threads while we avoid blocking.
It turns out that we need to design the application in such a way that there is no need for locks. Which is not always possible.
Or is there any solution? I will be grateful for any information.
There is no official implementation, here are some resources for reference.
How to trigger Mono execution after another Mono terminates
https://github.com/chenggangpro/reactive-lock

Rewriting a threaded Objective-C 'story engine' in CoffeeScript: How to script actions & conditions sequentially without a ton of callbacks?

I have been experimenting with porting the underlying 'story engine' of my Objective-C iPhone adventure Scarlett and the Spark of Life to HTML5 using CoffeeScript (and I am looking into IcedCoffeeScript).
The graphical part can just use DIVs on the DOM — the requirements there are fairly simple. The problematic part is the 'command and control' story-type commands. The ideal is to be able to express high-level story commands — including conditionals — and have them executed sequentially. So, for example, in faux-CoffeeScript:
scarlett.walkTo(200,300)
scarlett.turnTo(0)
story.wait(0.8)
if interesting
scarlett.think('Looks interesting.')
else
scarlett.think('Looks boring.')
In Objective-C (this was back when scripting languages like Lua were banned on the App Store), we achieved this by having two threads. The main thread ran cocos2d-phone which handled all the OpenGL calls, animation and other cocos niceties. The 'story' thread handled the command-and-control of the story, and if necessary the thread would sleep, awaiting an NSCondition before returning from a function and proceeding to the next call.
It sounds awkward, but it allowed us to express story commands and conditionals in a sequential, natural way, just using normal-looking code. Note that in the example above, the if check for the variable interesting would be evaluated right before Scarlett says something, not at the start of the function. Also, the walkTo(), turnTo(), wait() and think() calls will not return until their associated animation, delay or text box is finished back on the main thread.
What I'm struggling with is how to achieve this expressiveness using web technologies. As I see it, my options are:
Using a Web Worker as the story 'thread'. However, as far as I'm aware, workers can't sleep, and state isn't shared so they can't even perform a busy wait.
Using a callback chain, probably utilising IcedCoffeeScript's await and defer keywords to keep the code tidier. Even with those, though, that's a lot of extra line noise.
Somehow evaluate lines from the story script one-by-one as strings. I can't help feeling that it would be highly problematic.
(Similar in some ways to 3.) Write the story commands in a specially-designed interpreted language, where the program counter could be stopped and started as needed. It seems like this is unnecessarily re-inventing the wheel.
I can't help feeling like I'm overlooking some really obvious solution, though. Am I looking at this back-to-front, somehow? Is there an acknowledged pattern for scripting sequential actions and conditionals over time using actual code, without a mountain of callbacks?

When Would Anyone Want To Use NSThreads over the GCD?

Are there any cases when anyone would want to use raw NSThreads instead of GCD for concurrency? I love the GCD, but I want to know if I will need to use NSThreads for Cocoa/Cocoa-Touch eventually.
i use pthreads for control, good performance, and portability. sometimes, you might opt to use NSThread for the extra NSObject interfacing it offers.
there are a few lower level interfaces where you need to coordinate threads with the APIs you use (e.g. realtime I/O or rendering). sometimes you have flexibility regarding the thread you use, sometimes it is convenient to use NSThread in this situation so you can easily use CF or NS run loops with these interfaces. So the run loop parameter you set up on your thread is likely of more interest to the API than the thread itself. in these cases, GCD may not necessarily be an alternative.
but… most devs won't need to drop to these levels often.
You should essentially almost never need to use the NSThread/pthread APIs directly on OS X or iOS. On other platforms, possibly yes (though GCD is becoming more widely ported to *BSD, Linux and even Windows - see Wikipedia page for Grand Central Dispatch), but on Apple OS platforms you're almost always going to get a better result by allowing the system to do thread lifecycle management for you. The only case where you might conceivably want to do your own thread management are in highly real-time scenarios where you need to manage thread priorities and have direct control over thread latency by balancing the amount of work each thread is doing by hand.
There may be some special situations where you have to do something strange that cannot be done with GCD. But anything that you can do with GCD you should do it that way (GCD and threads are not mutually exclusive, if you need to actually use a thread you need not change any of the GCD stuff you already have).
Not sure however what the case would be. Maybe if you need to setup a secondary specialized RunLoop (not sure if it can be done with GCD but surely it can with a thread). Or there may be some other special case I cannot figure at the moment.

How should I design notifications in Cocoa if I plan to optimize for concurrency later?

In my app, I want to create a class that receives a certain type of notifications, begins it's work and sends out notifications when it's done. I think that later I may need to use concurrency to optimize the app — so this work that the class does is done in separate threads — but right now I don't have any knowledge or experience of working with concurrency and I don't want to spend time on premature optimizaion. However, if I understand correctly, the default usage of notifications doesn't mix with concurrency so well.
Is there a way that I can just follow few simple rules with notifications right now without diving into concurrency, and avoid rewriting all that code later?
Yes, you can avoid a rewrite.
I would write your work/background tasks inside blocks and use GCD (Grand Central Dispatch). This works fine and is easy to use in the non-parallel case, but will also allow you to easily parallelize your work later.
I'd look into NSBlockOperation and NSOperationQueue and/or dispatch_async()