Queue Thread In Blackberry - blackberry

I've looked at the BB API(5.0) and I can't find any way of serially executing a batch of threads. I know BB has a limit on the number of threads it will launch, so I don't want to launch 7 if the user clicks through things fast enough but I cannot find anything like a thread pool.
Is there an easy fix for this or do I have to create a data structure?

If you just want to execute a bunch of tasks on a single thread serially and order isn't important, you could create a Timer object (which has its own thread) then add each task to it as a TimerTask. If you schedule it with a delay of 0 or 1, it will essentially run that task as soon as possible. And since a Timer only has a single thread, if you schedule multiple tasks concurrently, it will ensure that only one will run at a time.
Incidentally, I was talking to a RIM engineer at the BlackBerry Developer Conference this year and he said that as of OS 5.0 there are no longer limits to the number of threads -- so this is becoming less and less of a concern.

I've tested Jeff Heaton's Thread Pool example on 4.5 and it works. (http://www.informit.com/articles/article.aspx?p=30483&seqNum=1).

Related

What is the difference between DispatchQueue schedule() vs DispatchQueue async() vs DispatchQueue concurrentPerform() for iOS Application

What are the differences between DispatchQueue schedule(), DispatchQueue async() and DispatchQueue concurrentPerform()?
Under what circumstances will it be more appropriate to use each?
I could not find much resource that says the difference between these three.
I went through these:
Links: schedule, concurrentPerform, async, Raywenderlich, AppCoda , EonCodes and few others.
The async is just for asynchronously dispatching a task to a queue (running it as soon as the queue can). It is used to dispatch some block of code to another queue. For example, one might call it from the main thread it to dispatch computationally expensive code off to some background queue, to avoid blocking the main thread. Or, if you are already on a background queue, you use it to dispatch code that must run on the main thread back to the main queue (e.g., UI updates). You can also use asyncAfter if you want to specify when this dispatched task should run (e.g., after a specified time/delay).
The schedule is an API that largely serves the same purpose as async/asyncAfter, but was introduced with Combine in iOS 13. It just dispatches blocks of code to run on the specified queue, optionally with some delay (or other constraints). If you need to support older iOS versions before iOS 13, just use async/asyncAfter instead. But if you are supporting contemporary iOS versions (especially if you are using Combine), then you can use this API if you want.
The concurrentPerform serves a very different functional need, namely if you are for dispatching a block of code repeatedly and in parallel to as many worker threads as your device can support. It is often used when writing computationally intense and massively parallelized routines. It is uniquely well suited for solving those cases where you might otherwise have “thread explosion”. (The number of worker threads that can be used at any given moment at time is quite limited and if you exceed this, your app can deadlock if you accidentally “explode” how many threads you are trying to use at any moment in time.) So for example, if you want to run hundreds or thousands of iterations, in parallel, concurrentPerform automatically constrains the degree of concurrency to the capabilities of your device (e.g. if you have 8 cores in your device, it only runs a maximum of 8 concurrent tasks at any given time). Think of this as a for loop where the various iterations run in parallel with each other. But unless you are writing massively parallelized code, you might not need to ever use this. But when you are, it is extremely useful.

Understanding Multithreading in iOS

I am trying to understand multi-threading on iOS in more detail. I went through some of the class references like NSThread, NSRunLoop, NSTask..
First of all as indicated on the following link:
use of runloop
Runloop runs within a Thread.
So why do we need to define our own Runloop in our app? In the case of NSThread it is useful because some of time-consuming processes can run in a separate thread so that the app will still be responsive on the main thread.
Interacting with the thread's run loop may be useful if you have a thread whose work you want to continue periodically. That is, a run loop would do some work, and then when it is finished with that work, it would put the thread to rest for some time, then resume work at a later time -- effectively preventing the thread from exiting. You won't need to interact with them or configure/create them yourself regularly (only a small percentage of apps would qualify, if you are using high level abstractions such as Foundation because Foundation would set them up on your behalf in most scenarios).
If your secondary thread just does a specified task and does not need to wait for some external event (e.g. a download to finish), you would (typically) not need to interact with the run loop.
You might consider looking at using NSOperationQueues, NSOperations and NSBlockOperations instead as these will manage themselves, will allow for cancellation of tasks and can be scheduled on main and background threads.

Ask Scheduler to schedule a certain thread

In Linux, with POSIX threads, is it possible to hint the scheduler to schedule a particular thread. Actually the scenario is that I have a process which is replica of another process. For deterministic execution, the follower process needs to acquire the locks in the same order as the leader process.
So for example, say in leader process, mutex a is locked by first thread 2, then 3 and 4. The follower must execute in the same order. So if in follower, thread 3 first encounters mutex a, I want thread 3 to say to the scheduler, ok I'm giving up my time slice, please schedule thread 2 instead. I know this can be achieved by modifying the scheduler, but I do not want that, I want to be able to control this from user space program.
In any system, Linux, Windows POSIX or not, if you have to ask this sort of question then I'm afraid that your app is heading for a dark place :(
Even if thread 3 were to yield, say with sleep(0), an interrupt straight after might well just schedule thread 3 back on again, preempting thread 2, or the OS might run thread 3 straightaway on another free core and it could get to the mutex first.
You have to make your app work correctly, (maybee not optimally), independently of the OS scheduling/dispatching algorithms. Even if you get your design to work on a test box, you will end up having to test your system on every combination of OS/hardware to ensure that it still works without deadlocking or performing incorrectly.
Fiddling with scheduling algorithms, thread priorities etc. should only be done to improve the performance of your app, not to try and make it work correctly or to stop it locking up!
Rgds,
Martin

Sleep performance

I am developing a program in c++ and I have to implement a cron. This cron should be executed every hour and every 24 hours for different reasons. My first idea was to make an independent pthread and sleep it during 1h every time. Is this correct? I mean, is really efficient to have a thread asleep more than awake? What are the inconvenients of having a thread slept?
I would tend to prefer to have such a task running via cron/scheduler since it is to run at pre-determined intervals, as opposed to in response to some environmental event. So the program should just 'do' what ever it needs to do, and then be executed by the operating system as needed. This also makes it easy to change the frequency of execution - just change the scheduling, rather than needing to rebuild the app or expose extra configurability.
That said, if you really, really wanted to do it that way, you probably would not sleep for the whole hour; You would sleep in multiple of some smaller time frame (perhaps five minutes, or what ever seems appropriate) and have a variable keeping the 'last run' time so you know when to run again.
Sleep() calls typically won't be exceptionally accurate as far as the time the thread ends up sleeping; it depends on what other threads have tasks waiting, etc.
There is no performance impact of having a thread sleeping for a long time, aside of the fact that it will occupy some memory without doing anything useful. Maybe if you'd do it for thousands of threads there would be some slow down in the OS's management of threads, but it doesn't look like you are planning to do that.
A practical disadvantage of having a thread sleep for long is, that you can't do anything with it. If you, for example, want to tell the thread that it should stop because the application wants to shut down, the thread could only get this message after the sleep. So your application either needs a very long time to shut down, or the thread will need to be stopped forcefully.
My first idea was to make an independent pthread and sleep it during 1h every time.
I see no problem.
Is this correct? I mean, is really efficient to have a thread asleep more than awake?
As long as a thread sleeps and doesn't wake up, OS wouldn't even bother with its existence.
Though otherwise, if thread sleeps most of its life, why to have a dedicated thread? Why other thread (e.g. main thread) can't check the time, and start a thread to do the cron job?
What are the inconvenients of having a thread slept?
None. But the fact that the sleeping thread cannot be easily unblocked. That is a concern if one needs proper shutdown of an application. That is why it is a better idea to have another (busy) thread to check the time and start the cron job when needed.
When designing your solution keep these scenarios in mind:
At 07:03 the system time is reset to 06:59. What happens one minute later?
At 07:03 the system time is moved forward to 07:59. What happens one minute later?
At 07:59 the system time is moved forward to 08:01. Is the 08:00-job ever executed?
The answers to those questions will tell you a lot about how you should implement your solution.
The performance of the solution should not be an issue. A single sleeping thread will use minimal resources.

BackgroundWorker Thread - C#

I have to do 3 async operations parallely inside a Windows NT Service (using .Net2.0/C#). For that I am using Backgroundworker component.
Is it a good option/approach?
For continuous operation, I am calling RunWorkerAsync() again in RunWorkerCompleted event.
Please suggest me.
Usually BackgroundWorker is used for long-time operations. If you just need to execute 3 tasks in parallel you can use simple threads.
Usually, BackgroundWorker is used when you need RunWorkerCompleted to perform updates in a GUI. At least that's how I've been using it. It sounds like you want this to run constantly, so why not use a regular worker thread?
The biggest issue I see is that BackgroundWorker uses the .NET thread pool, so if you really want this to run continuously, you've just guaranteed to use up one of the thread pool threads, of which there are a limited number available.
I wouldn't be using backgroundworkers for the job you're describing here.
The background worker is meant to be used for some 'long' running operations while keeping a responsive UI. Using services breaks the UI pattern.
For a service I would be using a timer and three threads.
Let the timer check the existence of the three threads and restart them or report errors when needed. The three threads can do their own job in a while loop (don't forget to add a sleep(0) in there)

Resources