This document provides an overview of Grand Central Dispatch (GCD) in iOS. It describes key GCD concepts like blocks, dispatch queues, operation queues, dispatch groups, and dispatch semaphores. It explains how to define and execute tasks using these constructs. Examples are given showing how to download images asynchronously and use callback blocks. References for further reading on GCD are also provided.
Blocks is a cool concept and is very much needed for performance improvements and responsiveness. GCD helps run blocks effortlessly by scheduling on a desired queue, priority and lots more.
Blocks is a cool concept and is very much needed for performance improvements and responsiveness. GCD helps run blocks effortlessly by scheduling on a desired queue, priority and lots more.
Java has a solid Memory Model, and there are a couple of excellent libraries for concurrency. When you start working with threads however, pitfalls start appearing - especially if the program is supposed to be fast and correct. This session shows proven solutions for some typical problems, showing how to view program code from a concurrency perspective: Which threads share which data, and how? How to reduce the impact of locks? How to avoid them altogether - and when is that worth it?
A fast Message-Queue base on zookeeper.
Jafka mq is a distributed publish-subscribe messaging system cloning from Apache Kafka.
So it has following features:
(1)Persistent messaging with O(1) disk structures that provide constant time performance even with many TB of stored messages.
(2)High-throughput: even with very modest hardware single broker can support hundreds of thousands of messages per second.
(3)Explicit support for partitioning messages over broker servers and distributing consumption over a cluster of consumer machines while maintaining per-partition ordering semantics.
(4)Simple message format for many language clients.
Project Loom is one of the most important change coming to JDK. The talk explores the Constraints and benefits of the request pre thread model and why there is a big push towards Aysnc frameworks.
How Project Loom and Structured Concurrency And Project Loom gives a new design paradigm to write scalable maintainable code
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
In this tutorial, we will build a to-do app using Vue Composition API & Vuex 4 with Typescript. We will learn and explore Composition API & Options API as well
At first glance, writing concurrent programs in Java seems like a straight-forward task. But the devil is in the detail. Fortunately, these details are strictly regulated by the Java memory model which, roughly speaking, decides what values a program can observe for a field at any given time. Without respecting the memory model, a Java program might behave erratic and yield bugs that only occure on some hardware platforms. This presentation summarizes the guarantees that are given by Java's memory model and teaches how to properly use volatile and final fields or synchronized code blocks. Instead of discussing the model in terms of memory model formalisms, this presentation builds on easy-to follow Java code examples.
Java has a solid Memory Model, and there are a couple of excellent libraries for concurrency. When you start working with threads however, pitfalls start appearing - especially if the program is supposed to be fast and correct. This session shows proven solutions for some typical problems, showing how to view program code from a concurrency perspective: Which threads share which data, and how? How to reduce the impact of locks? How to avoid them altogether - and when is that worth it?
A fast Message-Queue base on zookeeper.
Jafka mq is a distributed publish-subscribe messaging system cloning from Apache Kafka.
So it has following features:
(1)Persistent messaging with O(1) disk structures that provide constant time performance even with many TB of stored messages.
(2)High-throughput: even with very modest hardware single broker can support hundreds of thousands of messages per second.
(3)Explicit support for partitioning messages over broker servers and distributing consumption over a cluster of consumer machines while maintaining per-partition ordering semantics.
(4)Simple message format for many language clients.
Project Loom is one of the most important change coming to JDK. The talk explores the Constraints and benefits of the request pre thread model and why there is a big push towards Aysnc frameworks.
How Project Loom and Structured Concurrency And Project Loom gives a new design paradigm to write scalable maintainable code
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
In this tutorial, we will build a to-do app using Vue Composition API & Vuex 4 with Typescript. We will learn and explore Composition API & Options API as well
At first glance, writing concurrent programs in Java seems like a straight-forward task. But the devil is in the detail. Fortunately, these details are strictly regulated by the Java memory model which, roughly speaking, decides what values a program can observe for a field at any given time. Without respecting the memory model, a Java program might behave erratic and yield bugs that only occure on some hardware platforms. This presentation summarizes the guarantees that are given by Java's memory model and teaches how to properly use volatile and final fields or synchronized code blocks. Instead of discussing the model in terms of memory model formalisms, this presentation builds on easy-to follow Java code examples.
Opportunities in Resource Management Industries in Tees ValleyCatherineGordon2022
Free online guide to Opportunities in Resource Management Industries in Tees Valley now available...
Tees Valley Unlimited is working to attract jobs and investment to our area. To this end, we\'ve created a free, online guide for companies around the UK, to showcase our offer and capabilities in resource management industries.
Government\'s Review of Waste Strategy published in June 2011 restated Government\'s commitment to move towards a "zero waste" economy, recognising waste as a source of renewable energy and gave commitments to encourage and support both energy from waste and anaerobic digestion projects.
Tees Valley has expertise and potential across all elements of the emerging low carbon economy from anaerobic digestion (AD), heat waste and gasification to bioethanol, WEEE and the decommissioning of large structures.
Global energy players like Air Products, SITA and Sembcorp have all recently announced major investments in Tees Valley which, combined with the area\'s proven research capability in anaerobic digestion, biotechnology and bioremediation, reinforces the Tees Valley credentials as a leading low and zero waste hotspot.
To find out how Tees Valley can help position your company at the front of a growing UK industry, read on.
Nesta palestra, eu apresentei um resumo das principais novas características e melhorias do .NET Framework 4.5 para desenvolvedores da plataforma .NET. Eu abordei os seguintes tópicos:
O .NET Framework
.NET Framework: Versões
Linguagem C#: Versões
Suporte a async & await
Biblioteca de classes portátil
.NET para Windows Store apps
Entity Framework 5
ASP.NET Web Forms 4.5
ASP.NET MVC 4
Windows Communication Foundation (WCF) 4.5
Windows Presentation Foundation (WPF) 4.5
Windows Workflow Foundation (WF) 4.5
Melhorias na Base Class Library
Links úteis
O padrão <strong>IAsyncResult Pattern</strong> ou <strong>Asynchronous Programming Model (APM)</strong> foi introduzido no .NET Framework 1.0, em fevereiro de 2002. Também conhecido como <strong>Begin/End Pattern</strong>, num nível básico, o padrão se baseia em dois métodos relacionados para representar uma operação assíncrona: <strong>Begin</strong><em>NomeOperacao</em> e <strong>End</strong><em>NomeOperacao</em>.
Programação assíncrona com C# 5 no Visual Studio 2013 [MVP ShowCast 2013 - DE...Rogério Moraes de Carvalho
Palestra: Programação assíncrona com C# 5 no Visual Studio 2013
Palestrante: Rogério Moraes de Carvalho (MVP Visual C#)
Realização: 03/12/2013 17h
Trilha: Ferramentas de desenvolvimento & Linguagens de programação
Sessão: Desenvolvimento
Evento: MVP ShowCast 2013
Site: http://mvpshowcast.azurewebsites.net
Gives a brief introduction into some of the hidden tips and tricks with coding using Objective C, It gives examples for Literals ,Sub-scripting , Method swizzling
So you are a young, inexperienced iOS developer preparing for your first ever interview. But you don’t know what they are going to throw at you during the interview. During your student’s life you have been searching for the answers, this is the first time you are looking for the questions. This power point presentation is the right answer for your quest of looking for the interview questions. These are the probable questions interviewee may ask you for the post of iOS developer. Good luck.
Created by: Cygnis Media
Top technology trends in supply chain & logistics industryArindam Bakshi
Technology plays a very important part in determining the success of a supply chain. This e-book is primarily meant to inform you about the present day technologies that are heavily involved in determining the efficiency and productivity of the logistics and supply chain industry.
These are the slides which were used by Kumar Rajeev Rastogi of Huawei for his presentation at pgDay Asia 2016. He presented great idea about Native Compilation to improve CPU efficiency.
It talks about native compilation technology, why it is required, what it is?
Also how we can apply this technology to compile table and procedure to achieve considerable performance gain with very minimal changes.
MongoDB is the trusted document store we turn to when we have tough data store problems to solve. For this talk we are going to go a little bit off the path and explore what other roles we can fit MongoDB into. Others have discussed how to turn MongoDB’s capped collections into a publish/subscribe server. We stretch that a little further and turn MongoDB into a full fledged broker with both publish/subscribe and queue semantics, and a the ability to mix them. We will provide code and a running demo of the queue producers and consumers. Next we will turn to coordination services: We will explore the fundamental features and show how to implement them using MongoDB as the storage engine. Again we will show the code and demo the coordination of multiple applications.
The traditional database executors are based on the fact that “I/O cost dominates execution”. These executor models are inefficient in terms of CPU instructions.
Now most of the workloads fits into main memory so biggest bottleneck is actually CPU.
Our goal is to make executor more efficient in terms of CPU efficiency by making specializing the code.
Here we discuss about one kind of specialization i.e. relation access method specialization.
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxbradburgess22840
In Class Assignmetz/CST280W13a-1.pdf
CST 280 In-Class Practice – Week 13
Manually determine the configuration of the priority queue (stored as a heap) created
by the following operations. Trace the following logic and define the output:
enqueue(7);
enqueue(17);
enqueue(2);
enqueue(5);
enqueue(22);
enqueue(19);
enqueue(6);
enqueue(11);
enqueue(13);
write the queue contents
dequeue and write front item
enqueue(15);
enqueue(8);
dequeue and write front item
dequeue and write front item
enqueue(24);
enqueue(14);
write the queue contents
Part 2
Then, verify the output by implementing the algorithm by rewriting the priority
queue demonstration program discussed in class. Files needed:
testPQueue.cpp pqType.h heap.cpp
Deliverables
• This cover sheet (with your names on it)
• Driver source code and output for verification program exectution.
In Class Assignmetz/CST280W13b.pdf
CST 280 In-Class Practice – Week 13
Use this page as a worksheet to sketch the progression of the elements up to the first
split for the QuickSort algorithm. Use the middle array element as the split value:
15 34 99 42 11 41 66 23 55 93 48
Next, access the file quickSort.cpp from the course web page. Tailor the program
by entering the array values above in place of the integer values used for an in-class
demonstration. Be sure to adjust the index range to match the size of this array.
Remember that the parameters to the QuickSort algorithm are starting and ending index
values, not the size of the array.
Next, insert code to demonstrate the state of the array after the first split. This should
verify what you did by hand above. Insert the following code at various points within
the partition function to “see” the array at various stages of processing:
for (int i = start; i <= end; i++) // <== ADD
cout << set[i] << ' ';
cout << endl;
Insert the code at these positions:
int partition(int set[], int start, int end)
{
int pivotValue, pivotIndex, mid;
mid = (start + end) / 2;
swap(set[start], set[mid]);
pivotIndex = start;
pivotValue = set[start];
ç HERE
for (int scan = start + 1; scan <= end; scan++)
{
if (set[scan] < pivotValue)
{
pivotIndex++;
swap(set[pivotIndex], set[scan]);
}
ç HERE
}
swap(set[start], set[pivotIndex]);
ç HERE
return pivotIndex;
}
Finally, identify the line that matches what you concluded above.
Deliverables:
Deliver the following for this assignment:
• This work sheet with a sketch of the array first split
• Program source code with required change
• Program output demonstrating array configuration after first split .
Gephi Toolkit Developer Tutorial.
The Gephi Toolkit project package essential modules (Graph, Layout, Filters, IO...) in a standard Java library, which any Java project can use for getting things done. The toolkit is just a single JAR that anyone could reuse.
This tutorial introduce the project, show possibilities and code examples to get started.
This presentation is about multitasking with std::future.
Presentation by Dmytro Gurin (Lead Software Engineer, GlobalLogic, Kyiv), delivered at GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-MallaSpark Summit
Spark had been elected, deservedly, as the main massive parallel processing framework, and HDFS is the one of the most popular Big Data storage technologies. Therefore its combination is one of the most usual Big Data’s use cases. But, what happens with the security? Can these two technologies coexist in a secure environment? Furthermore, with the proliferation of BI technologies adapted to Big Data environments, that demands that several users interacts with the same cluster concurrently, can we continue to ensure that our Big Data environments are still secure? In this lecture, Abel and Jorge will explain which adaptations of Spark´s core they had to perform in order to guarantee the security of multiple concurrent users using a single Spark cluster, which can use any of its cluster managers, without degrading the outstanding Spark’s performance.
The primary focus of this presentation is approaching the migration of a large, legacy data store into a new schema built with Django. Includes discussion of how to structure a migration script so that it will run efficiently and scale. Learn how to recognize and evaluate trouble spots.
Also discusses some general tips and tricks for working with data and establishing a productive workflow.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
3. GCD: An Overview
Concurrency
do multiple things simultaneously
take advantage of multiple cores
Traditional way: create multiple threads
not efficiently: unused or overused cores
low-level, waste time to create and destroy thread
thread programming is hard
Modern way: Grand Central Dispatch (GCD)
4. GCD: An Overview
easier, more modern and efficient than threads
high-level, move thread management down to system level
define tasks and add them to an appropriate dispatch queues
task management and execution is more efficient than threads
new concepts: task and dispatch queues
5. GCD: An Overview
in waiting
a queue - FIFO
put task into queue dequeued tasks
to execute are being executed
if there are some queues, they could still execute tasks concurrently
6. Blocks
blocks
task is defined by using block
blocks are an extension of C language
encapsulate code like a function by using ^{ … }
define blocks
// Simple one
void (^myblock)() = ^{
printf(“Hellon”);
};
myblock(); //executing block
7. Blocks (cont.)
with arguments
void (^myblock)(int) = ^(int arg){
printf(“Helloarg=%dn”,arg);
};
myblock(1);
with return value
int (^myblock)(int) = ^(int arg){
printf(“Hello arg=%dn”,arg);
return arg+1;
};
int r = myblock(1);
http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blo
cks/Articles/bxGettingStarted.html#//apple_ref/doc/uid/TP40007502-CH7-SW1
8. Dispatch Queues
Overview
dispatch queues
C based, procedural programming
easy way to perform tasks asynchronously and concurrently
add a task into the queues to perform it
3-types of dispatch queues
serial (private dispatch queue) execute one task at a time
concurrent (global dispatch queue) execute one or more task concurrently
main dispatch queues execute task on main thread
9. Dispatch Queues
Creating dispatch queues
dispatch_queue_t queue;
// Main (serial) queue
queue = dispatch_get_main_queue();
// User (serial) queue
queue = dispatch_queue_create(“com.mycompany.qname”, NULL);
// Global (concurrent) queue, with priority
queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
notes:
there are 3 global queues by priority: HIGH, DEFAULT, LOW
you can create as many serial queue as you need
10. Dispatch Queues
Adding tasks to a queue
synchronous
// Synchronous, blocks until code is executed
dispatch_sync(queue, ^{
//taskcode
});
asynchronous
// Asynchronous, returns immediately to caller
dispatch_async(queue, ^{
//taskcode
});
dispatch_after(when, queue, ^{
//taskcode
});
11. Dispatch Queues
more
suspend a queue
dispatch_suspend(queue);
resume a queue
dispatch_resume(queue);
memory management
Dispatch queues are reference-counted data types.When you create a serial
dispatch queue, it has an initial reference count of 1.You can use the
dispatch_retain and dispatch_release functions to increment
and decrement that reference count as needed. When the reference count of
a queue reaches zero, the system asynchronously deallocates the queue.
13. Operation Queues
Creating operations
by selector
NSInvocationOperation* theOp = [[NSInvocationOperation alloc]
initWithTarget:self selector:@selector(myTaskMethod:) object:data];
by block
NSBlockOperation *operation = [NSBlockOperation
blockOperationWithBlock:^{
NSLog(@"Doing something...");
}];
//you can add more blocks
[operation addExecutionBlock:^{
NSLog(@"Another block");
}];
[operation setCompletionBlock:^{
NSLog(@"Doing something once the operation has finished");
}];
14. Operation Queues
Executing operations
adding operation to NSOperationQueue
NSOperationQueue* aQueue = [[NSOperationQueue alloc] init];
[aQueue addOperation:anOp]; // Add a single operation
// Add multiple operations
[aQueue addOperations:anArrayOfOps waitUntilFinished:NO];
[aQueue addOperationWithBlock:^{
/* Do something. */
}];
You can execute operations manually by reading document from:
http://developer.apple.com/library/ios/#documentation/General/
Conceptual/ConcurrencyProgrammingGuide/OperationObjects/Operation
Objects.html#//apple_ref/doc/uid/TP40008091-CH101-SW1
15. Operation Queues
More
suspending and resuming operation queues
- (void)setSuspended:(BOOL)suspend
cancels all queued and executing operation
- (void)cancelAllOperation
reference links:
https://developer.apple.com/library/mac/#documentation/Cocoa/Refe
rence/NSOperationQueue_class/Reference/Reference.html
https://developer.apple.com/library/mac/#documentation/Cocoa/Refe
rence/NSOperation_class/Reference/Reference.html
16. Dispatch Group
use to group some blocks and track when they all complete
it can be helpful when progress can’t be made until all of the specified
tasks are complete
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group,queue,^{
NSLog(@"Block 1");
});
dispatch_group_async(group,queue,^{
NSLog(@"Block 2");
});
dispatch_group_notify(group,queue,^{
NSLog(@"Final block is executed last after 1 and 2");
});
17. Dispatch Semaphore
In computer science, a semaphore is a variable or abstract data type that provides
a simple but useful abstraction for controlling access by multiple processes to a
common resource in a parallel programming or multi user environment.
(wikipedia)
use a dispatch semaphore to regulate the number of tasks simultaneously
accessing some resources
// Create the semaphore, specifying the initial pool size
dispatch_semaphore_t fd_sema = dispatch_semaphore_create
(getdtablesize() / 2);
// Wait for a free file descriptor
dispatch_semaphore_wait(fd_sema, DISPATCH_TIME_FOREVER);
fd = open("/etc/services", O_RDONLY);
// Release the file descriptor when done
close(fd);
dispatch_semaphore_signal(fd_sema);
18. Examples
Example 1: Download Image with dispatch queue
dispatch_queue_t queue = dispatch_queue_create(”image_queue”
, NULL);
//dispatch_async to get the image data
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL:
[NSURL URLWithString:url]];
UIImage *anImage = [UIImage imageWithData:data];
[self.images setValue:anImage forKey:userID];
UITableViewCell *cell = [self.tableView
cellForRowAtIndexPath:indexPath];
//dispatch_async on the main queue to update the UI
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = anImage;
});
});
run a heavy work on background and update GUI on main thread
19. Examples
Example 2: Callback block
#import "ASIHTTPRequest.h”
- (void)getImage {
__block ASIHTTPRequest *request = [ASIHTTPRequest
requestWithURL:sourceURL];
[request setCompletionBlock:^{
NSLog(@"Image downloaded.");
NSData *data = [request responseData];
image = [[UIImage alloc] initWithData:data];
}];
[request setFailedBlock:^{
NSLog(@"Error downloading image");
}];
[request startAsynchronous];
}
the OS will automatically run the code to download the image on a
background thread, and call one of the callback blocks when it completes or fails!
Our topic today is Grand Central Dispatch.It takes about 15 minutes to covers all issues
Here are contents of my presentation
Firstly, I want to talk about an overview of GCDGCD is a new technology to perform concurrent programming.As you know, creating multiple threads is traditional way to do this.Assume, if you want to download a file in background, you will have to create a thread and attach this work on this thread.But threading is not efficient because it doesn’t take advantage of multiple core efficiently.
So that apple has invented GCD to do concurrency easier, more modern and efficient.It moves thread management down to system level.All you have to do is only creating tasks and putting them into dispatch queues.
You can see it more “ro rang” in this picture.Two steps to perform concurrently a task. Defines a task and put it into the dispatch queues.
Let’s go to step 1.You define a task by using block.Blocks are an extension of C language.To define a block you simply “wraps” code in ^{ .. }