I'm new to working with concurrency in Objective-C. I've taken look at some demo codes of concurrency programming.
I want to print natural numbers sequentially but in 2 different threads. Like:
1
: Thread-XX
2
: Thread-YY
3
: Thread-XX
4
: Thread-YY
5
: Thread-XX
6
: Thread-YY.....................
.....................
and so on. But I can't figure out how to do that. Any help?
We can show you how to do this, but it's not a very useful scenario. You're going to spent a lot of time coordinating these two threads with semaphores or the like, largely diminishing the value of having stuff running on multiple threads. Often when you write multithreaded code, you want to maximize concurrency by minimizing the amount of time spent waiting for some signal from some other thread. This attempt to alternate between these two threads is antithetical to our general intent of multithreaded programming.
That having been said, it could look a bit like:
Usually when we're updating one variable from multiple threads, we'd synchronize our access to that object, but this "have the threads alternate" logic eliminates our need to do that, in this particular case.