Erlang is a programming language for building highly parallel, distributed, fault-tolerant systems. This is the second part of a two-part introduction.
On March 2014, Java 8 was released. These informal slides describe the new elements of the programming languages, focusing on those taken from the functional paradigm.
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
Object-Oriented Programming has well established design principles, such as SOLID. For many developers architecture and functional programming are at odds with each other: they don’t know how their existing tricks of the trade convert into functional design. This problem becomes worse as hybrid languages such as Java 8 or Scala become common. We’ll talk about how functional programming helps you implement the SOLID principles, and how a functional mindset can actually help you achieve cleaner and simpler OO design.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
On March 2014, Java 8 was released. These informal slides describe the new elements of the programming languages, focusing on those taken from the functional paradigm.
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
Object-Oriented Programming has well established design principles, such as SOLID. For many developers architecture and functional programming are at odds with each other: they don’t know how their existing tricks of the trade convert into functional design. This problem becomes worse as hybrid languages such as Java 8 or Scala become common. We’ll talk about how functional programming helps you implement the SOLID principles, and how a functional mindset can actually help you achieve cleaner and simpler OO design.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
In a nutshell, an Arduino is an open hardware development board that can be used by tinkerers, hobbyists, and makers to design and build devices that interact with the real world. While Arduino refers to a specific type of board design, it can also be used to refer to a company which manufactures a specific implementation of these boards, and is typically also used to describe the community around compatible boards made by other people or companies which function in a similar way.
These are my slides from a mini Clojure tutorial presented at the "7 Languages in 7 Months" meetup group. The first part of the presentation faithfully presents material from Bruce Tate book, and the second part covers the more advanced topics of state management and macros
In a nutshell, an Arduino is an open hardware development board that can be used by tinkerers, hobbyists, and makers to design and build devices that interact with the real world. While Arduino refers to a specific type of board design, it can also be used to refer to a company which manufactures a specific implementation of these boards, and is typically also used to describe the community around compatible boards made by other people or companies which function in a similar way.
These are my slides from a mini Clojure tutorial presented at the "7 Languages in 7 Months" meetup group. The first part of the presentation faithfully presents material from Bruce Tate book, and the second part covers the more advanced topics of state management and macros
This is my monthly Real Estate Newsletter focused on East Windsor in particular, but Mercer, Middlesex, Monmouth, Ocean, and Burlington counties in general. I hope it's helpful.
e-Book ini dibuat berdasarkan catatan dan pengalaman penulis dalam periode 2013-2015 yang memberikan gambaran mengenai bentang alam, kegiatan masyarakat dan keanekaragaman hayati yang ada di wilayah Kerinci Indonesia
Национальная Ассоциация Сельского, Экологического, Культурного Туризма Молдовы это неправительственная, некоммерческая, вне политики организация. ANTREC-Молдова является первой профессиональной ассоциации сельского туризма в стране, которые создали сеть гостиниц. Более подробную информацию вы можете найти на нашем сайте http://www.moldova-tourism.md/
QCON SP 2016 - Elixir: Tolerância a Falhas para AdultosFabio Akita
Elixir é uma das novas linguagens que está despontando principalmente pela reputação de capacidade de altíssima concorrência e paralelismo que sua VM permite. Mas o principal elemento é que Erlang e por consequência, Elixir, é uma das poucas linguagens criadas assumindo que vamos cometer erros. Ele garante alta disponibilidade nos dando primitivas que permitam que nosso software continue funcionando, mesmo que às vezes ele falhe. E agora vamos ver como Erlang faz isso como Elixir expõe esse potencial a todos nós.
Parsing binaries and protocols with erlangBhasker Kode
Delivered by Bhasker V Kode at foss.in/2009
Official talk page at http://foss.in/2009/schedules/talkdetailspub.php?talkid=17
Erlang 's support for handling binaries and pattern matching make it a great choice for parsing everything from IPv4 packets, to payloads from the Memcached protocol, SWF files, or databases like Tokyo Cabinet. From a functional programming perspective, there are various ways of building these parsers, taking advantage of the concurrent and recursive nature that is inherent to the language and other challenges which have been gathered while validating the storage & retrieval options for our distributed crawler, and submitting patches to projects like Medici & Tora ( erlang based Tokyo Cabinet clients). The talk will also touch upon Tokyo cabinet's support for mapreduce with Lua, and notes from building your own custom formats & our internal mapreduce'esque and caching frameworks used in building a multi-million impression platform utilizing under a gig of RAM per node.
Notes on:
- trends in disk/memory/bandwidth
- why erlang, RAM, binaries
- garbage collection in the erlang VM
- message passing
- use-cases
Multiplatform JIT Code Generator for NetBSD by Alexander Nasonoveurobsdcon
Abstract
The next release of NetBSD will have a support for Just-In-Time (JIT) compilation of bpf programs in the kernel; this change will greatly speed-up traffic sniffing on multiple platforms. Unlike similar interface in other operating systems, bpfjit uses a unified programming interface for code generation which is based on Stack Less JIT Compiler library (SLJIT) and which supports x86, mips, arm, sparc and some other platforms.
The speaker will give an overview of SLJIT API and discuss some implementation details of the bpfjit code with emphasis on supported optimizations of bpf programs by JIT engine. He will also touch on unit testing of dynamically generated code running inside the kernel and on other areas in the NetBSD project where bpfjit can help in boosting performance."
Speaker bio
Alex is a software developer working in the financial sector in the City of London. He often amuses fellow tube passengers with C or Lua coding in NetBSD console and sometimes even with the green kernel debugger prompt.
Kernel Recipes 2019 - Formal modeling made easyAnne Nicolas
Modeling parts of Linux has become a recurring topic. For instance, the memory model, the model for PREEMPT_RT synchronization, and so on. But the term "formal model" causes panic for most of the developers. Mainly because of the complex notations and reasoning that involves formal languages. It seems to be a very theoretical thing, far from our day-by-day reality.
Believe me. Modeling can be more practical than you might guess!
This talk will discuss the challenges and benefits of modeling, based on the experience of developing the PREEMPT_RT model. It will present a methodology for modeling the Linux behavior as Finite-State Machines (automata), using terms that are very known by kernel developers: tracing events! With the particular focus on how to use models for the formal verification of Linux kernel, at runtime, with low overhead, and in many cases, without even modifying Linux kernel!
Daniel Bristot de Oliveira
What is program and process .
Program execution flow .
Example of process generation .
Description of process .
Types of process .
Ways of run process .
How process is generated using fork() and execution .
Process life cycle .
Process tree .
Process states .
Load Averages .
For monitoring and managing linux process tools .
A discussion of Erlang/OTP, based on the "A History of Erlang" paper, with the addition of covering some of the methods used in the paper that enable Riak to be a highly reliable, distributed datastore, while leveraging the work of giants.
Locks? We Don't Need No Stinkin' Locks - Michael BarkerJAX London
Embrace the dark side. As a developer you'll often be advised that writing concurrent code should be the purview of the genius coders alone. In this talk Michael Barker will discard that notion into the cesspits of logic and reason and attempt to present on the less understood area of non-blocking concurrency, i.e. concurrency without locks. We'll look the modern Intel CPU architecture, why we need a memory model, the performance costs of various non-blocking constructs and delve into the implementation details of the latest version of the Disruptor to see how non-blocking concurrency can be applied to build high performance data structures.
Using Complex Network Analysis for PeriodizationDmitry Zinoviev
Periodization is the process of categorizing the past into discrete, contiguous, quantified, and named blocks of time and the results of such a process. I propose to model historical states as complex networks and use complex network analysis (CNA) for periodization.
The majority of the USA population still believe people with serious mental illness (SMI) are dangerous. SMI and dangerousness have been recurring topics of newspaper coverage for some time. What aspects, if any, have been associated in mainstream American media with SMI? Are there historical periods where significant sociopolitical events have occurred e.g., war, economic depression, immigration shifts, that have impacted the balance of positive and negative those aspects?
Roles and Words in a massive NSSI-Related Interaction NetworkDmitry Zinoviev
Non-suicidal self-injury (NSSI), such as self-cutting or self-burning, is the deliberate destruction of one’s body tissue in the absence of suicidal intent. Approximately one in five of adolescents and one in four of young adults in the USA often referred to as “self-cutters,” have engaged in NSSI. The goal of the study is to analyze the topology of an interaction network of the NSSI-related users and compare it to the vocabulary of the blog posts and comments.
Network analysis of the 2016 USA presidential campaign tweetsDmitry Zinoviev
This is an IC2S2 presentation.
Donald Trump has been an avid user of Twitter before, throughout, and in the aftermath of the 2017 USA presidential election campaign. Secretary Hillary Clinton, the Democratic Party candidate, was active on Twitter only from the beginning to end of the campaign. The goal of this research is to reconstruct the timeline and logic of the campaign using complex network analysis of President Trump's and Secretary Clinton's tweets.
We analyzed 20,000 tweets posted by Trump in January 2014--December 2017, covering all three major stages of his quest for the Presidency. The tweets are composed of 14,373 distinct, unstemmed terms (words, word combinations, and hashtags). For further analysis, we selected only 300 base terms that occurred in the whole corpus at least 100 times. We grouped the tweets by months into 48 tweet corpora and converted them into a network, based on the similarity of the vocabulary. Each network node represents a monthly corpus. We connected two nodes with a weighted edge if the frequencies of the base terms in the corresponding corpora were strongly correlated (with the Pearson correlation coefficient, serving as the weight of the edge, at or above 0.6).
The corpus consists of two clusters: April 2015 (when Clinton announced her intention to run)--March 2016 and April 2016--November 2016 (the general election). Interestingly, the boundary between the clusters corresponds to the campaign stages, too---but those of Trump rather than Clinton: it is located in the middle of the Republican Party primary elections. We hypothesize that throughout the campaign Secretary Clinton was in the defensive position and had to respond to the challenges posed by Trump, rather than form her agenda (at least on Twitter). We will further look into the cross-correlations between the tweet corpora of the two major presidential candidates to get a better sense of their ``leader-follower'' relationship.
An example of how automated text analysis leads, through social network construction, to recognition of key plot lines and characters in a fiction book.
Soviet Popular Music Landscape: Community Structure and Success PredictorsDmitry Zinoviev
More than 4,600 non-academic music groups emerged in the USSR and post-Soviet independent nations in 1960–2015, performing in 275 genres and sub-genres, including rock, pop, disco, jazz, and folk. Some of the groups became legends and survived for decades, while others vanished and are known now only to select music history scholars and fans. The total number of unique performers in all groups exceeds 17,000, and at least 3,600 of them participated in more than one project.
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Atelier - Innover avec l’IA Générative et les graphes de connaissancesNeo4j
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Allez au-delà du battage médiatique autour de l’IA et découvrez des techniques pratiques pour utiliser l’IA de manière responsable à travers les données de votre organisation. Explorez comment utiliser les graphes de connaissances pour augmenter la précision, la transparence et la capacité d’explication dans les systèmes d’IA générative. Vous partirez avec une expérience pratique combinant les relations entre les données et les LLM pour apporter du contexte spécifique à votre domaine et améliorer votre raisonnement.
Amenez votre ordinateur portable et nous vous guiderons sur la mise en place de votre propre pile d’IA générative, en vous fournissant des exemples pratiques et codés pour démarrer en quelques minutes.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
2. 2
Concurrency
● A deep understanding of concurrency is “hardwired” into our brains
● The world is parallel
● Erlang programs model how we think and interact:
– No shared memory
● People function as independent entities who communicate by sending
messages:
– Erlang is based on pure message passing
– No locking needed
● If somebody dies, other people will notice:
– Processes can be linked together
3. 3
Erlang Processes
● Erlang processes belong to the programming language, not to the OS
– Creating and destroying processes is very fast
– Sending messages between processes is very fast
– Processes behave the same way on all operating systems
– A very large number of processes is feasible
– Processes share no memory and are completely independent
– Creating a process takes 4–5ms
– The only way for processes to interact is through message passing
4. 4
Concurrency Primitives
● Pid = spawn(Fun)
– Create a new concurrent process that evaluates Fun. The primitive
returns the process identifier
● Pid ! Message
– Send Message to the process Pid. The send is nonblocking
(asynchronous). The value of the expression is the message itself.
Therefore, Pid1 ! Pid2 ! ... ! PidN ! M sends M to all mentioned
processes
● receive ... end
– Receive a message according to a pattern.
6. 6
Client-server
● Actually, “request-response”
● To receive a response, a request must contain the pid of the requester
● Received responses must be matched with pending requests with the
help of pid's and, if necessary, sequence numbers
● Requests can be disguised as (remote) procedure calls
8. 8
Client-server example (cont.)
%% At shell prompt
1> Pid = area_server_final:start().
<0.36.0>
2> area_server_final:area(Pid, {rectangle, 10, 8}).
80
9. 9
Receive with timeout and guards
● receive...end can have and optional after clause that takes Time in
milliseconds and returns an expression if no message is received after
Time. Time can be infinity.
● The receive clause itself can be empty. Good for timers:
sleep(T) -> receive after T -> true end.
● A timeout value can be 0. Good for flushing mailboxes:
flush_mailbox() ->
receive _Any -> flush_buffer()
after 0 -> true
end.
● Any pattern in the receive clause can have a when guard.
11. 11
Registered processes
● A pid can be published. A process with a published pid becomes a
registered process.
● register(atom, Pid)
– Register the process Pid with the name atom.
● unregister(atom)
– Remove the registration. If a registered process dies it will be
automatically unregistered.
● whereis(atom) -> Pid | undefined
– Find out whether atom is registered, and if so, what's its Pid
● registered() -> AtomList
– Return a list of all registered processes
14. 14
Linking processes
● If a process in some way depends on another, then it may keep an eye
on the health of that second process using links and monitors
● Built-in function (BIF) link(Pid) links processes
● BIF spawn_link(Fun) -> Pid spawns a linked process—to avoid race
conditions
● BIF unlink(Pid) unlinks linked processes
● If A and B are linked and one of them dies, the other receives an exit
signal and will die, too—unless it is a system process
● A system process can trap exit signals
● BIF process_flag(trap_exit, true) makes a process a system process
15. 15
on_exit handler: example
%% If Pid dies, execute Fun in yet another process
on_exit (Pid, Fun) ->
spawn(fun() ->
process_flag(trap_exit, true),
link(Pid),
receive
{'EXIT', Pid, Why} ->
Fun(Why)
end
end).
16. 16
A keep-alive process
%% This function will keep a registered process alive!
keep_alive(Name, Fun) ->
register(Name, Pid = spawn(Fun)),
on_exit(Pid, fun(_Why) -> keep_alive(Name, Fun) end).
%% Unfortunately, this code has a race condition:
%% The new process can dies before the handler is registered!
17. 17
Going distributed
● Distributed programs run on networks of computers and coordinate
their activities only by message passing
● Reasons for having distributed programs:
– Performance
– Reliability
– Scalability
– Support for intrinsically distributed applications (games, chats)
– Fun :)
● Trusted or untrusted environment? Distributed Erlang vs TCP/IP
sockets
18. 18
Development sequence
● Write and test a program in a regular nondistributed Erlang session
● Test the program on several different Erlang nodes running on the
same computer
● Test the program on several different Erlang nodes running on several
physically separated computers either in the same local area network
or anywhere on the Internet
19. 19
A simple key-value server (kvs)
-module(kvs).
-export([start/0,store/2,lookup/1]).
start()->register(kvs, spawn(fun()->loop() end)).
store(Key, Value)->rpc({store, Key, Value}).
lookup(Key) -> rpc({lookup, Key}).
rpc(Q)-> .... %% as defined earlier
loop() ->
receive
{From, {store, Key, Value}} -> put(Key, {ok, Value}),
From ! {kvs, true}, loop();
{From, {lookup, Key}} -> From ! {kvs, get(Key)}, loop()
end.
21. 21
A better rpc
● Standard Erlang libraries have packages rpc that provides a number of
remote procedure call services, and global that has functions for the
registration of names and locks (if necessary)
● call(Name, Mod, Function, ArgList) -> Result | {badrpc, Reason}
● For two Erlang nodes to communicate, they must share the same
cookie:
– put the cookie in ~/.erlang.cookie (make it user-readable)
– start Erlang shell with -setcookie parameter
– use erlang:set_cookie(node(), C) BIF
22. 22
Two nodes, same host
astra:~/Erlang/> erl -sname aspera
Erlang (BEAM) emulator version 5.6.5 [source] [async-threads:0] [hipe]
[kernel-poll:false]
Eshell V5.6.5 (abort with ^G)
(aspera@astra)1> kvs:start().
true
---------------------------------------------------------------------
astra:~/Erlang/> erl -sname astra
Erlang (BEAM) emulator version 5.6.5 [source] [async-threads:0] [hipe]
[kernel-poll:false]
Eshell V5.6.5 (abort with ^G)
(astra@astra)1> rpc:call(aspera@astra,kvs,store,[weather,fine]).
true
(astra@astra)2> rpc:call(aspera@astra,kvs,lookup,[weather]).
{ok,fine}
23. 23
Two nodes, two different hosts
● Start Erlang with the -name parameter (not -sname)
● Ensure that both nodes have the same cookie
● Make sure that DNS works
● Make sure that both hosts have the same version of the code that you
want to run
– Simply copy the code
– Use network file system (NFS)
– Use a code server (advanced)
– Use the shell command nl(Mod). This loads the module Mod on all
connected nodes.
24. 24
More distribution primitives
● disconnect_node(Node) -> bool() | ignored
– forcefully disconnects a node
● node() -> Node
– returns the name of the local node
● node(Arg) -> Node
– returns the node where Arg (a PID, a reference, or a port) is located
● nodes() -> [Node]
– returns a list of all other connected nodes
● is_alive() -> bool()
– returns true if the local node is alive
25. 25
Remote spawn
● spawn(Node,Fun) -> Pid
– this works exactly like spawn(Fun)—but remotely
● spawn(Node, Mod, Func, ArgList) -> Pid
– same as above; this function will not break if the distributed nodes
do not run exactly the same version of a particular module
● spawn_link(Node, Func) -> Pid
● spawn_link(Node, Mod, Func, ArgList)
26. 26
A note on security
● Distributed Erlang should be used only in a trusted environment
● In an unstrusted network, use TCP/IP (module gen_tcp) or UDP/IP
(module gen_udp) sockets
27. 27
Using TCP: example 1 (client)
%% socket_example.erl
nano_get_url() -> nano_get_url(“www.google.com”).
nano_get_url(Host) ->
{ok, Socket} = gen_tcp:connect(Host,80,[binary, {packet, 0})],
ok = gen_tcp:send(Socket, “GET / HTTP/1.0rnrn”),
receive_data(Socket, []).
receive_data(Socket, SoFar) ->
receive
{tcp,Socket,Bin} -> receive_data(Socket, [Bin|SoFar]);
{tcp_closed,Socket} -> list_to_binary(reverse(SoFar))
end.
%% On the shell command line:
1> string:tokens(binary_to_list(socket_examples:nano_get_url),”rn”).
%% But of course there is a standard function http:request(Url) !
29. 29
Programming with files
● Erlang supports (through module file):
– Reading all Erlang terms from a file at once
– Reading Erlang terms from a file one at a time and writing them
back
– Reading files line by line and writing lines into a file
– Reading an entire file into a binary and writing a binary to a file
– Reading files randomly
– Getting file info
– Working with directories
– Copying and deleting files
30. 30
This presentation roughly covers the second 27
pages (of the total of 29
) of
“Programming Erlang. Software for a Concurrent World,” by Joe
Armstrong.