SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Concurrent programming
By-
Tausun Akhtary
Software Analyst
Ipvision Canada Inc
Source : Apple Documentations and
Internet Research
Concurrent Programming
Concurrency describes the concept of running several tasks at the same time. This can either
happen in a time-shared manner on a single CPU core, or truly in parallel if multiple CPU cores are
available.
Concurrent program is a program that has different execution path that run simultaneously.
- Bishnu Pada Chanda,
IPVision Canada Inc
Parallel vs Concurrent
Concurrency means that two or
more calculations happen within the
same time frame, and there is
usually some sort of dependency
between them.
Parallelism means that two or more
calculations happen simultaneously.
Concurrency/Multitasking
Multitasking allows several activities to occur concurrently on the computer
● Levels of multitasking:
○ Process-based multitasking : Allows programs (processes) to run concurrently
○ Thread-based multitasking (multithreading) : Allows parts of the same process (threads)
to run concurrently
Merits of concurrent Programming/Multitasking
● Speed
● Availability
● Distribution
Thread
Only CSE people can understand Thread and String are not the same.
● In computer science, a thread of execution is the smallest sequence of programmed
instructions that can be managed independently by a scheduler, which is typically a part of
the operating system.
● The implementation of threads and processes differs between operating systems, but in most
cases a thread is a component of a process.
● Multiple threads can exist within one process, executing concurrently (one starting before
others finish) and share resources such as memory, while different processes do not share
these resources. In particular, the threads of a process share its instructions (executable
code) and its context (the values of its variables at any given time).
Thread States
Concurrency via Thread
Concurrency challenges
● Shared resource
● Race condition
● Critical section
Concurrency challenges
● Mutual exclusion
Concurrency challenges
● Deadlock
void swap(A, B)
{
lock(lockA);
lock(lockB);
int a = A;
int b = B;
A = b;
B = a;
unlock(lockB);
unlock(lockA);
}
swap(X, Y); // thread 1
swap(Y, X); // thread 2
Concurrency challenges
● Priority Inversion
● Starvation
Lock, Mutex, Semaphore
● Semaphores have a synchronized counter and mutex's are just binary (true / false).
● A semaphore is often used as a definitive mechanism for answering how many elements of a
resource are in use -- e.g., an object that represents n worker threads might use a
semaphore to count how many worker threads are available.
● Truth is you can represent a semaphore by an INT that is synchronized by a mutex.
Mutex vs Semaphore (the toilet example)
● Mutex
○ Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When
finished, the person gives (frees) the key to the next person in the queue.
● Semaphore
○ Is the number of free identical toilet keys. Example, say we have four toilets with
identical locks and keys. The semaphore count - the count of keys - is set to 4 at
beginning (all four toilets are free), then the count value is decremented as people are
coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0.
Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key),
and given to the next person in the queue.
Concurrency in ios
Apple provides :
● Threads
● Grand Central Dispatch
● Dispatch Queue
● Dispatch source
● OPeration Queue
● Synchronization
Synchronization in ios
● Atomic operation
○ #include <libkern/OSAtomic.h>, mathematical and logical operations on 32-bit and 64-bit values
○ Does not block anything, lighter than synchronized
● Memory Barriers
○ A memory barrier is a type of nonblocking synchronization tool used to ensure that memory operations occur
in the correct order. A memory barrier acts like a fence, forcing the processor to complete any load and store
operations positioned in front of the barrier before it is allowed to perform load and store operations positioned
after the barrier.
○ Simply call the OSMemoryBarrier function
● Volatile Variables
○ Applying the volatile keyword to a variable forces the compiler to load that variable from memory each time it
is used. You might declare a variable as volatile if its value could be changed at any time by an external
source that the compiler may not be able to detect
Synchronization in ios
● Locks
○ Mutex - A mutually exclusive (or mutex) lock acts as a protective barrier around a resource. A mutex is a type
of semaphore that grants access to only one thread at a time.
○ Recursive lock - A recursive lock is a variant on the mutex lock. A recursive lock allows a single thread to
acquire the lock multiple times before releasing it. Other threads remain blocked until the owner of the lock
releases the lock the same number of times it acquired it. Recursive locks are used during recursive iterations
primarily but may also be used in cases where multiple methods each need to acquire the lock separately.
○ Read-write lock - A read-write lock is also referred to as a shared-exclusive lock. This type of lock is typically
used in larger-scale operations and can significantly improve performance if the protected data structure is
read frequently and modified only occasionally. During normal operation, multiple readers can access the data
structure simultaneously. When a thread wants to write to the structure, though, it blocks until all readers
release the lock, at which point it acquires the lock and can update the structure. While a writing thread is
waiting for the lock, new reader threads block until the writing thread is finished. The system supports read-
write locks using POSIX threads only.
Synchronization in ios
● Locks
○ Distributed lock - A distributed lock provides mutually exclusive access at the process level. Unlike a true
mutex, a distributed lock does not block a process or prevent it from running. It simply reports when the lock is
busy and lets the process decide how to proceed.
○ Spin lock - A spin lock polls its lock condition repeatedly until that condition becomes true. Spin locks are most
often used on multiprocessor systems where the expected wait time for a lock is small. In these situations, it is
often more efficient to poll than to block the thread, which involves a context switch and the updating of thread
data structures. The system does not provide any implementations of spin locks because of their polling
nature, but you can easily implement them in specific situations.
○ Double-checked lock - A double-checked lock is an attempt to reduce the overhead of taking a lock by testing
the locking criteria prior to taking the lock. Because double-checked locks are potentially unsafe, the system
does not provide explicit support for them and their use is discouraged.
Synchronization in ios
● Conditions
○ A condition is another type of semaphore that allows threads to signal each other when a certain condition is
true. Conditions are typically used to indicate the availability of a resource or to ensure that tasks are
performed in a specific order. When a thread tests a condition, it blocks unless that condition is already true. It
remains blocked until some other thread explicitly changes and signals the condition. The difference between
a condition and a mutex lock is that multiple threads may be permitted access to the condition at the same
time. The condition is more of a gatekeeper that lets different threads through the gate depending on some
specified criteria.
○ One way we might use a condition is to manage a pool of pending events. The event queue would use a
condition variable to signal waiting threads when there were events in the queue. If one event arrives, the
queue would signal the condition appropriately. If a thread were already waiting, it would be woken up
whereupon it would pull the event from the queue and process it. If two events came into the queue at roughly
the same time, the queue would signal the condition twice to wake up two threads.
Synchronization in ios
● Performselector
○ Each request to perform a selector is queued on the target thread’s run loop and the requests are then
○ Processed sequentially in the order in which they were received.
● @synchronized
○ The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The
@synchronized directive does what any other mutex lock would do—it prevents different threads from
acquiring the same lock at the same time.
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.
html
Thread management ios
Each process (application) in OS X or iOS is made up of one or more threads, each of which
represents a single path of execution through the application's code. Every application starts with a
single thread, which runs the application's main function. Applications can spawn additional
threads, each of which executes the code of a specific function.
● Creating an Autorelease Pool
○ Managed memory model - strictly needed
○ Garbage collecting model - not necessary but using is not harmful
Because,
1. The top-level autorelease pool does not release its objects until the thread exits, long-lived threads should create
additional autorelease pools to free objects more frequently.
2. A thread that uses a run loop might create and release an autorelease pool each time through that run loop.
Releasing objects more frequently prevents your application’s memory footprint from growing too large, which can
lead to performance problems.
Thread management ios
● Setting Up an Exception Handler
○ If our application catches and handles exceptions, the thread code should be prepared to catch any
exceptions that might occur. Although it is best to handle exceptions at the point where they might occur,
failure to catch a thrown exception in a thread causes your application to exit.
○ Installing a final try/catch in the thread entry routine allows to catch any unknown exceptions and provide an
appropriate response.
Thread management ios
● Setting Up a Run Loop
○ To run code segment on a separate thread, there are two options.
■ The first option is to write the code for a thread as one long task to be performed
with little or no interruption, and have the thread exit when it finishes.
■ The second option is put the thread into a loop and have it process requests
dynamically as they arrive. This option, involves setting up the thread’s run loop.
● Terminating a Thread
○ Let it exit naturally(Recommended)
○ To kill the thread,
Threads
pthread
OS X and iOS provide C-based
support for creating threads using
the POSIX thread API. This
technology can actually be used in
any type of application (including
Cocoa and Cocoa Touch
applications) and might be more
convenient if you are writing your
software for multiple platforms.
#include <assert.h>
#include <pthread.h>
void* PosixThreadMainRoutine(void* data)
{
// Do some work here.
return NULL;
}
void LaunchThread()
{
// Create the thread using POSIX routines.
pthread_attr_t attr;
pthread_t posixThreadID;
int returnVal;
returnVal = pthread_attr_init(&attr);
assert(!returnVal);
returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
assert(!returnVal);
int threadError = pthread_create(&posixThreadID, &attr, &PosixThreadMainRoutine,
NULL);
returnVal = pthread_attr_destroy(&attr);
assert(!returnVal);
if (threadError != 0)
{
// Report an error.
}
}
NSThread
NSThread is a simple Objective-C wrapper
around pthreads. This makes the code look
more familiar in a Cocoa environment. For
example, you can define a thread as a
subclass of NSThread, which encapsulates
the code you want to run in the background.
For the previous example, we could define an
NSThread subclass like this:
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector
(myThreadMainMethod:)
object:nil];
[myThread start]; // Actually create the thread
or
[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:)
toTarget:self withObject:nil];
GCD(Grand Central Dispatch)
● Grand Central Dispatch (GCD) was introduced in OS X 10.6 and iOS 4 in order to make it
easier for developers to take advantage of the increasing numbers of CPU cores in consumer
devices.
● With GCD you don’t interact with threads directly anymore. Instead you add blocks of code to
queues
● GCD manages a thread pool behind the scenes.
● GCD decides on which particular thread your code blocks are going to be executed on, and it
manages these threads according to the available system resources.
● The other important change with GCD is that you as a developer think about work items in a
queue rather than threads. This new mental model of concurrency is easier to work with.
GCD
Dispatch Queues
● Dispatch queues allows us to execute arbitrary blocks of code either asynchronously or
synchronously
● All Dispatch Queues are first in – first out
● All the tasks added to dispatch queue are started in the order they were added to the
dispatch queue.
● Dispatch Queue Types
○ Serial (also known as private dispatch queue)
○ Concurrent
○ Main Dispatch Queue
Dispatch Sources
A dispatch source is a fundamental data type that coordinates the processing of specific low-level
system events. Grand Central Dispatch supports the following types of dispatch sources:
●Timer dispatch sources generate periodic notifications.
●Signal dispatch sources notify you when a UNIX signal arrives.
●Descriptor sources notify you of various file- and socket-based operations, such as:
○When data is available for reading
○When it is possible to write data
○When files are deleted, moved, or renamed in the file system
○When file meta information changes
●Process dispatch sources notify you of process-related events, such as:
○When a process exits
○When a process issues a fork or exec type of call
○When a signal is delivered to the process
●Some other system events
Dispatch Source Example
dispatch_source_t CreateDispatchTimer(uint64_t interval,
uint64_t leeway,
dispatch_queue_t queue,
dispatch_block_t block)
{
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,
0, 0, queue);
if (timer)
{
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval, leeway);
dispatch_source_set_event_handler(timer, block);
dispatch_resume(timer);
}
return timer;
}
void MyCreateTimer()
{
dispatch_source_t aTimer = CreateDispatchTimer(30ull * NSEC_PER_SEC,
1ull * NSEC_PER_SEC,
dispatch_get_main_queue(),
^{ MyPeriodicTask(); });
// Store it somewhere for later use.
if (aTimer)
{
MyStoreTimer(aTimer);
}
Operation Queues
● NSInvocationOperation
● NSBlockOperation
● NSOperation
NSInvocationOperation
@implementation MyCustomClass
- (NSOperation*)taskWithData:(id)data {
NSInvocationOperation* theOp = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(myTaskMethod:) object:data];
return theOp;
}
// This is the method that does the actual work of the task.
- (void)myTaskMethod:(id)data {
// Perform the task.
}
@end
NSBlockOperation
NSBlockOperation* theOp = [NSBlockOperation blockOperationWithBlock: ^{
NSLog(@"Beginning operation.n");
// Do some work.
}];
NSOperation
@interface MyNonConcurrentOperation : NSOperation
@property id (strong) myData;
-(id)initWithData:(id)data;
@end
@implementation MyNonConcurrentOperation
- (id)initWithData:(id)data {
if (self = [super init])
myData = data;
return self;
}
-(void)main {
@try {
// Do some work on myData and report the results.
}
@catch(...) {
// Do not rethrow exceptions.
}
}
@end
Thank You :)

Weitere ähnliche Inhalte

Was ist angesagt?

Inter process communication
Inter process communicationInter process communication
Inter process communication
Mohd Tousif
 

Was ist angesagt? (20)

Distributed operating system(os)
Distributed operating system(os)Distributed operating system(os)
Distributed operating system(os)
 
Operating system memory management
Operating system memory managementOperating system memory management
Operating system memory management
 
Code optimization in compiler design
Code optimization in compiler designCode optimization in compiler design
Code optimization in compiler design
 
Storage Management
Storage ManagementStorage Management
Storage Management
 
Inter process communication
Inter process communicationInter process communication
Inter process communication
 
Recognition-of-tokens
Recognition-of-tokensRecognition-of-tokens
Recognition-of-tokens
 
Web Security
Web SecurityWeb Security
Web Security
 
Distributed Operating System_1
Distributed Operating System_1Distributed Operating System_1
Distributed Operating System_1
 
Operating system 11 system calls
Operating system 11 system callsOperating system 11 system calls
Operating system 11 system calls
 
Telnet
TelnetTelnet
Telnet
 
Shared-Memory Multiprocessors
Shared-Memory MultiprocessorsShared-Memory Multiprocessors
Shared-Memory Multiprocessors
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)
 
Demand paging
Demand pagingDemand paging
Demand paging
 
RPC: Remote procedure call
RPC: Remote procedure callRPC: Remote procedure call
RPC: Remote procedure call
 
CS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMSCS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMS
 
Process management os concept
Process management os conceptProcess management os concept
Process management os concept
 
Operating systems system structures
Operating systems   system structuresOperating systems   system structures
Operating systems system structures
 
Interprocess communication (IPC) IN O.S
Interprocess communication (IPC) IN O.SInterprocess communication (IPC) IN O.S
Interprocess communication (IPC) IN O.S
 
IPC
IPCIPC
IPC
 
Amdahl`s law -Processor performance
Amdahl`s law -Processor performanceAmdahl`s law -Processor performance
Amdahl`s law -Processor performance
 

Andere mochten auch

Parallel programming
Parallel programmingParallel programming
Parallel programming
Swain Loda
 
Intro to parallel computing
Intro to parallel computingIntro to parallel computing
Intro to parallel computing
Piyush Mittal
 

Andere mochten auch (12)

Parallel programming
Parallel programmingParallel programming
Parallel programming
 
Concurrent programming in iOS
Concurrent programming in iOSConcurrent programming in iOS
Concurrent programming in iOS
 
An Introduction to Python Concurrency
An Introduction to Python ConcurrencyAn Introduction to Python Concurrency
An Introduction to Python Concurrency
 
Ateji PX for Java
Ateji PX for JavaAteji PX for Java
Ateji PX for Java
 
Intro to parallel computing
Intro to parallel computingIntro to parallel computing
Intro to parallel computing
 
Transactional Memory
Transactional MemoryTransactional Memory
Transactional Memory
 
Delphi Parallel Programming Library
Delphi Parallel Programming LibraryDelphi Parallel Programming Library
Delphi Parallel Programming Library
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel Programming
 
Multiprocessing with python
Multiprocessing with pythonMultiprocessing with python
Multiprocessing with python
 
SlidesA Comparison of GPU Execution Time Prediction using Machine Learning an...
SlidesA Comparison of GPU Execution Time Prediction using Machine Learning an...SlidesA Comparison of GPU Execution Time Prediction using Machine Learning an...
SlidesA Comparison of GPU Execution Time Prediction using Machine Learning an...
 
Java - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basicsJava - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basics
 
8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems
 

Ähnlich wie Concurrent/ parallel programming

Linux kernel development_ch9-10_20120410
Linux kernel development_ch9-10_20120410Linux kernel development_ch9-10_20120410
Linux kernel development_ch9-10_20120410
huangachou
 
Linux kernel development chapter 10
Linux kernel development chapter 10Linux kernel development chapter 10
Linux kernel development chapter 10
huangachou
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
Kaniska Mandal
 
Describe synchronization techniques used by programmers who develop .pdf
Describe synchronization techniques used by programmers who develop .pdfDescribe synchronization techniques used by programmers who develop .pdf
Describe synchronization techniques used by programmers who develop .pdf
excellentmobiles
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
koji lin
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
aviade
 
Aleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_DevelopmentAleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_Development
Ciklum
 

Ähnlich wie Concurrent/ parallel programming (20)

Linux kernel development_ch9-10_20120410
Linux kernel development_ch9-10_20120410Linux kernel development_ch9-10_20120410
Linux kernel development_ch9-10_20120410
 
Linux kernel development chapter 10
Linux kernel development chapter 10Linux kernel development chapter 10
Linux kernel development chapter 10
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
 
Describe synchronization techniques used by programmers who develop .pdf
Describe synchronization techniques used by programmers who develop .pdfDescribe synchronization techniques used by programmers who develop .pdf
Describe synchronization techniques used by programmers who develop .pdf
 
Concurrency in Java
Concurrency in JavaConcurrency in Java
Concurrency in Java
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
Memory model
Memory modelMemory model
Memory model
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuning
 
Aleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_DevelopmentAleksandr_Butenko_Mobile_Development
Aleksandr_Butenko_Mobile_Development
 
Introduction to concurrent programming with akka actors
Introduction to concurrent programming with akka actorsIntroduction to concurrent programming with akka actors
Introduction to concurrent programming with akka actors
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actors
 
Multi threading
Multi threadingMulti threading
Multi threading
 
MultiThreading in Python
MultiThreading in PythonMultiThreading in Python
MultiThreading in Python
 
Linux Locking Mechanisms
Linux Locking MechanismsLinux Locking Mechanisms
Linux Locking Mechanisms
 
gcdtmp
gcdtmpgcdtmp
gcdtmp
 

Kürzlich hochgeladen

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Kürzlich hochgeladen (20)

%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 

Concurrent/ parallel programming

  • 1. Concurrent programming By- Tausun Akhtary Software Analyst Ipvision Canada Inc Source : Apple Documentations and Internet Research
  • 2. Concurrent Programming Concurrency describes the concept of running several tasks at the same time. This can either happen in a time-shared manner on a single CPU core, or truly in parallel if multiple CPU cores are available. Concurrent program is a program that has different execution path that run simultaneously. - Bishnu Pada Chanda, IPVision Canada Inc
  • 3. Parallel vs Concurrent Concurrency means that two or more calculations happen within the same time frame, and there is usually some sort of dependency between them. Parallelism means that two or more calculations happen simultaneously.
  • 4. Concurrency/Multitasking Multitasking allows several activities to occur concurrently on the computer ● Levels of multitasking: ○ Process-based multitasking : Allows programs (processes) to run concurrently ○ Thread-based multitasking (multithreading) : Allows parts of the same process (threads) to run concurrently
  • 5. Merits of concurrent Programming/Multitasking ● Speed ● Availability ● Distribution
  • 6. Thread Only CSE people can understand Thread and String are not the same. ● In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system. ● The implementation of threads and processes differs between operating systems, but in most cases a thread is a component of a process. ● Multiple threads can exist within one process, executing concurrently (one starting before others finish) and share resources such as memory, while different processes do not share these resources. In particular, the threads of a process share its instructions (executable code) and its context (the values of its variables at any given time).
  • 9. Concurrency challenges ● Shared resource ● Race condition ● Critical section
  • 11. Concurrency challenges ● Deadlock void swap(A, B) { lock(lockA); lock(lockB); int a = A; int b = B; A = b; B = a; unlock(lockB); unlock(lockA); } swap(X, Y); // thread 1 swap(Y, X); // thread 2
  • 12. Concurrency challenges ● Priority Inversion ● Starvation
  • 13. Lock, Mutex, Semaphore ● Semaphores have a synchronized counter and mutex's are just binary (true / false). ● A semaphore is often used as a definitive mechanism for answering how many elements of a resource are in use -- e.g., an object that represents n worker threads might use a semaphore to count how many worker threads are available. ● Truth is you can represent a semaphore by an INT that is synchronized by a mutex.
  • 14. Mutex vs Semaphore (the toilet example) ● Mutex ○ Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue. ● Semaphore ○ Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.
  • 15. Concurrency in ios Apple provides : ● Threads ● Grand Central Dispatch ● Dispatch Queue ● Dispatch source ● OPeration Queue ● Synchronization
  • 16. Synchronization in ios ● Atomic operation ○ #include <libkern/OSAtomic.h>, mathematical and logical operations on 32-bit and 64-bit values ○ Does not block anything, lighter than synchronized ● Memory Barriers ○ A memory barrier is a type of nonblocking synchronization tool used to ensure that memory operations occur in the correct order. A memory barrier acts like a fence, forcing the processor to complete any load and store operations positioned in front of the barrier before it is allowed to perform load and store operations positioned after the barrier. ○ Simply call the OSMemoryBarrier function ● Volatile Variables ○ Applying the volatile keyword to a variable forces the compiler to load that variable from memory each time it is used. You might declare a variable as volatile if its value could be changed at any time by an external source that the compiler may not be able to detect
  • 17. Synchronization in ios ● Locks ○ Mutex - A mutually exclusive (or mutex) lock acts as a protective barrier around a resource. A mutex is a type of semaphore that grants access to only one thread at a time. ○ Recursive lock - A recursive lock is a variant on the mutex lock. A recursive lock allows a single thread to acquire the lock multiple times before releasing it. Other threads remain blocked until the owner of the lock releases the lock the same number of times it acquired it. Recursive locks are used during recursive iterations primarily but may also be used in cases where multiple methods each need to acquire the lock separately. ○ Read-write lock - A read-write lock is also referred to as a shared-exclusive lock. This type of lock is typically used in larger-scale operations and can significantly improve performance if the protected data structure is read frequently and modified only occasionally. During normal operation, multiple readers can access the data structure simultaneously. When a thread wants to write to the structure, though, it blocks until all readers release the lock, at which point it acquires the lock and can update the structure. While a writing thread is waiting for the lock, new reader threads block until the writing thread is finished. The system supports read- write locks using POSIX threads only.
  • 18. Synchronization in ios ● Locks ○ Distributed lock - A distributed lock provides mutually exclusive access at the process level. Unlike a true mutex, a distributed lock does not block a process or prevent it from running. It simply reports when the lock is busy and lets the process decide how to proceed. ○ Spin lock - A spin lock polls its lock condition repeatedly until that condition becomes true. Spin locks are most often used on multiprocessor systems where the expected wait time for a lock is small. In these situations, it is often more efficient to poll than to block the thread, which involves a context switch and the updating of thread data structures. The system does not provide any implementations of spin locks because of their polling nature, but you can easily implement them in specific situations. ○ Double-checked lock - A double-checked lock is an attempt to reduce the overhead of taking a lock by testing the locking criteria prior to taking the lock. Because double-checked locks are potentially unsafe, the system does not provide explicit support for them and their use is discouraged.
  • 19. Synchronization in ios ● Conditions ○ A condition is another type of semaphore that allows threads to signal each other when a certain condition is true. Conditions are typically used to indicate the availability of a resource or to ensure that tasks are performed in a specific order. When a thread tests a condition, it blocks unless that condition is already true. It remains blocked until some other thread explicitly changes and signals the condition. The difference between a condition and a mutex lock is that multiple threads may be permitted access to the condition at the same time. The condition is more of a gatekeeper that lets different threads through the gate depending on some specified criteria. ○ One way we might use a condition is to manage a pool of pending events. The event queue would use a condition variable to signal waiting threads when there were events in the queue. If one event arrives, the queue would signal the condition appropriately. If a thread were already waiting, it would be woken up whereupon it would pull the event from the queue and process it. If two events came into the queue at roughly the same time, the queue would signal the condition twice to wake up two threads.
  • 20. Synchronization in ios ● Performselector ○ Each request to perform a selector is queued on the target thread’s run loop and the requests are then ○ Processed sequentially in the order in which they were received. ● @synchronized ○ The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The @synchronized directive does what any other mutex lock would do—it prevents different threads from acquiring the same lock at the same time. https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety. html
  • 21. Thread management ios Each process (application) in OS X or iOS is made up of one or more threads, each of which represents a single path of execution through the application's code. Every application starts with a single thread, which runs the application's main function. Applications can spawn additional threads, each of which executes the code of a specific function. ● Creating an Autorelease Pool ○ Managed memory model - strictly needed ○ Garbage collecting model - not necessary but using is not harmful Because, 1. The top-level autorelease pool does not release its objects until the thread exits, long-lived threads should create additional autorelease pools to free objects more frequently. 2. A thread that uses a run loop might create and release an autorelease pool each time through that run loop. Releasing objects more frequently prevents your application’s memory footprint from growing too large, which can lead to performance problems.
  • 22. Thread management ios ● Setting Up an Exception Handler ○ If our application catches and handles exceptions, the thread code should be prepared to catch any exceptions that might occur. Although it is best to handle exceptions at the point where they might occur, failure to catch a thrown exception in a thread causes your application to exit. ○ Installing a final try/catch in the thread entry routine allows to catch any unknown exceptions and provide an appropriate response.
  • 23. Thread management ios ● Setting Up a Run Loop ○ To run code segment on a separate thread, there are two options. ■ The first option is to write the code for a thread as one long task to be performed with little or no interruption, and have the thread exit when it finishes. ■ The second option is put the thread into a loop and have it process requests dynamically as they arrive. This option, involves setting up the thread’s run loop. ● Terminating a Thread ○ Let it exit naturally(Recommended) ○ To kill the thread,
  • 24. Threads pthread OS X and iOS provide C-based support for creating threads using the POSIX thread API. This technology can actually be used in any type of application (including Cocoa and Cocoa Touch applications) and might be more convenient if you are writing your software for multiple platforms. #include <assert.h> #include <pthread.h> void* PosixThreadMainRoutine(void* data) { // Do some work here. return NULL; } void LaunchThread() { // Create the thread using POSIX routines. pthread_attr_t attr; pthread_t posixThreadID; int returnVal; returnVal = pthread_attr_init(&attr); assert(!returnVal); returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); assert(!returnVal); int threadError = pthread_create(&posixThreadID, &attr, &PosixThreadMainRoutine, NULL); returnVal = pthread_attr_destroy(&attr); assert(!returnVal); if (threadError != 0) { // Report an error. } }
  • 25. NSThread NSThread is a simple Objective-C wrapper around pthreads. This makes the code look more familiar in a Cocoa environment. For example, you can define a thread as a subclass of NSThread, which encapsulates the code you want to run in the background. For the previous example, we could define an NSThread subclass like this: NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector (myThreadMainMethod:) object:nil]; [myThread start]; // Actually create the thread or [NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];
  • 26. GCD(Grand Central Dispatch) ● Grand Central Dispatch (GCD) was introduced in OS X 10.6 and iOS 4 in order to make it easier for developers to take advantage of the increasing numbers of CPU cores in consumer devices. ● With GCD you don’t interact with threads directly anymore. Instead you add blocks of code to queues ● GCD manages a thread pool behind the scenes. ● GCD decides on which particular thread your code blocks are going to be executed on, and it manages these threads according to the available system resources. ● The other important change with GCD is that you as a developer think about work items in a queue rather than threads. This new mental model of concurrency is easier to work with.
  • 27. GCD
  • 28. Dispatch Queues ● Dispatch queues allows us to execute arbitrary blocks of code either asynchronously or synchronously ● All Dispatch Queues are first in – first out ● All the tasks added to dispatch queue are started in the order they were added to the dispatch queue. ● Dispatch Queue Types ○ Serial (also known as private dispatch queue) ○ Concurrent ○ Main Dispatch Queue
  • 29. Dispatch Sources A dispatch source is a fundamental data type that coordinates the processing of specific low-level system events. Grand Central Dispatch supports the following types of dispatch sources: ●Timer dispatch sources generate periodic notifications. ●Signal dispatch sources notify you when a UNIX signal arrives. ●Descriptor sources notify you of various file- and socket-based operations, such as: ○When data is available for reading ○When it is possible to write data ○When files are deleted, moved, or renamed in the file system ○When file meta information changes ●Process dispatch sources notify you of process-related events, such as: ○When a process exits ○When a process issues a fork or exec type of call ○When a signal is delivered to the process ●Some other system events
  • 30. Dispatch Source Example dispatch_source_t CreateDispatchTimer(uint64_t interval, uint64_t leeway, dispatch_queue_t queue, dispatch_block_t block) { dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); if (timer) { dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval, leeway); dispatch_source_set_event_handler(timer, block); dispatch_resume(timer); } return timer; } void MyCreateTimer() { dispatch_source_t aTimer = CreateDispatchTimer(30ull * NSEC_PER_SEC, 1ull * NSEC_PER_SEC, dispatch_get_main_queue(), ^{ MyPeriodicTask(); }); // Store it somewhere for later use. if (aTimer) { MyStoreTimer(aTimer); }
  • 31. Operation Queues ● NSInvocationOperation ● NSBlockOperation ● NSOperation
  • 32. NSInvocationOperation @implementation MyCustomClass - (NSOperation*)taskWithData:(id)data { NSInvocationOperation* theOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(myTaskMethod:) object:data]; return theOp; } // This is the method that does the actual work of the task. - (void)myTaskMethod:(id)data { // Perform the task. } @end NSBlockOperation NSBlockOperation* theOp = [NSBlockOperation blockOperationWithBlock: ^{ NSLog(@"Beginning operation.n"); // Do some work. }];
  • 33. NSOperation @interface MyNonConcurrentOperation : NSOperation @property id (strong) myData; -(id)initWithData:(id)data; @end @implementation MyNonConcurrentOperation - (id)initWithData:(id)data { if (self = [super init]) myData = data; return self; } -(void)main { @try { // Do some work on myData and report the results. } @catch(...) { // Do not rethrow exceptions. } } @end