This document discusses synchronization in operating systems and computer science. It covers topics like locks, mutexes, semaphores, and condition variables. Locks are used for mutual exclusion to ensure only one thread accesses a critical section at a time. Semaphores generalize locks and can be used to coordinate threads and signal events. Readers-writer locks allow multiple reader threads but only one writer thread for optimization. Common synchronization issues like deadlocks, priority inversion, and failures to unlock are also addressed.
A brief introduction to Process synchronization in Operating Systems with classical examples and solutions using semaphores. A good starting tutorial for beginners.
A brief introduction to Process synchronization in Operating Systems with classical examples and solutions using semaphores. A good starting tutorial for beginners.
Nowadays, CPU microarchitecture is concealed from developers by compilers, VMs, etc. Do Java developers need to know microarchitecture details of modern processors? Or, does it like to learn quantum mechanics for cooking? Are Java developers safe from leaking low-level microarchitecture details into high level application performance behaviour? We will try to answer these questions by analyzing several Java example.
Core Java Programming Language (JSE) : Chapter XII - ThreadsWebStackAcademy
What are Java Threads?
A thread is a:
Facility to allow multiple activities within a single process
Referred as lightweight process
A thread is a series of executed statements
Each thread has its own program counter, stack and local variables
A thread is a nested sequence of method calls
Its shares memory, files and per-process state
How to create thread:
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
Julien Ponge
This talk introduces part of the Java SE 7 novelties. The fork/join framework aims at making parallel programming simpler, while Project Coin brings a set of subtle yet useful changes to the Java programming language.
http://soft-shake.ch/2011/conference/sessions/java/2011/09/06/java7.html
Exception handling - Fundamentals of exception handling, Exception types, Termination or resumptive models, Uncaught exceptions, using try and catch, multiple catch clauses, nested try statements, throw, throws and finally, built- in exceptions, creating own exception sub classes.
Multithreading- Differences between thread-based multitasking and process-based multitasking, Java thread model, creating threads, thread priorities, synchronizing threads, inter thread communication
Similar to Operating Systems - Advanced Synchronization (20)
Doppio: Breaking the Browser Language BarrierEmery Berger
Web browsers have become a de facto universal operating system, and JavaScript its instruction set. Unfortunately, running other languages in the browser is not generally possible. Translation to JavaScript is not enough because browsers are a hostile environment for other languages. Previous approaches are either non-portable or require extensive modifications for programs to work in a browser.
This talk presents Doppio, a JavaScript-based runtime system that makes it possible to run unaltered applications written in general- purpose languages directly inside the browser. Doppio provides a wide range of runtime services, including a file system that enables local and external (cloud-based) storage, an unmanaged heap, sockets, blocking I/O, and multiple threads. We demonstrate Doppio's usefulness with two case studies: we extend Emscripten with Doppio, letting it run an unmodified C++ application in the browser with full functionality, and present DoppioJVM, an interpreter that runs unmodified JVM programs directly in the browser. While substantially slower than a native JVM, DoppioJVM makes it feasible to directly reuse existing, non compute-intensive code.
Dthreads is an efficient deterministic multithreading system for unmodified C/C++ applications that replaces the pthreads library. Dthreads enforces determinism in the face of data races and deadlocks. It is easy to use: just link your program with -ldthread instead of -lpthread.
Dthreads can be downloaded from its source code repo on GitHub (https://github.com/plasma-umass/dthreads). A technical paper describing Dthreads appeared at SOSP 2012 (https://github.com/plasma-umass/dthreads/blob/master/doc/dthreads-sosp11.pdf?raw=true).
Multithreaded programming is notoriously difficult to get right. A key problem is non-determinism, which complicates debugging, testing, and reproducing errors. One way to simplify multithreaded programming is to enforce deterministic execution, but current deterministic systems for C/C++ are incomplete or impractical. These systems require program modification, do not ensure determinism in the presence of data races, do not work with general-purpose multithreaded programs, or run up to 8.4× slower than pthreads.
This talk presents Dthreads, an efficient deterministic multithreading system for unmodified C/C++ applications that replaces the pthreads library. Dthreads enforces determinism in the face of data races and deadlocks. Dthreads works by exploding multithreaded applications into multiple processes, with private, copy-on-write mappings to shared memory. It uses standard virtual memory protection to track writes, and deterministically orders updates by each thread. By separating updates from different threads, Dthreads has the additional benefit of eliminating false sharing. Experimental results show that Dthreads substantially outperforms a state-of-the-art deterministic runtime system, and for a majority of the benchmarks we evaluated, matches and occasionally exceeds the performance of pthreads.
Humans can perform many tasks with ease that remain difficult or impossible for computers. Crowdsourcing platforms like Amazon's Mechanical Turk make it possible to harness human-based computational power on an unprecedented scale. However, their utility as a general-purpose computational platform remains limited. The lack of complete automation makes it difficult to orchestrate complex or interrelated tasks. Scheduling human workers to reduce latency costs real money, and jobs must be monitored and rescheduled when workers fail to complete their tasks. Furthermore, it is often difficult to predict the length of time and payment that should be budgeted for a given task. Finally, the results of human-based computations are not necessarily reliable, both because human skills and accuracy vary widely, and because workers have a financial incentive to minimize their effort.
This talk presents AutoMan, the first fully automatic crowdprogramming system. AutoMan integrates human-based computations into a standard programming language as ordinary function calls, which can be intermixed freely with traditional functions. This abstraction allows AutoMan programmers to focus on their programming logic. An AutoMan program specifies a confidence level for the overall computation and a budget. The AutoMan runtime system then transparently manages all details necessary for scheduling, pricing, and quality control. AutoMan automatically schedules human tasks for each computation until it achieves the desired confidence level; monitors, reprices, and restarts human tasks as necessary; and maximizes parallelism across human workers while staying under budget.
AutoMan is available for download at www.automan-lang.org.
Heap-based attacks depend on a combination of memory management errors and an exploitable memory allocator. Many allocators include ad hoc countermeasures against particular exploits, but their effectiveness against future exploits has been uncertain.
This paper presents the first formal treatment of the impact of allocator design on security. It analyzes a range of widely-deployed memory allocators, including those used by Windows, Linux, FreeBSD, and OpenBSD, and shows that they remain vulnerable to attack. It then presents DieHarder, a new allocator whose design was guided by this analysis. DieHarder provides the highest degree of security from heap-based attacks of any practical allocator of which we are aware, while imposing modest performance overhead. In particular, the Firefox web browser runs as fast with DieHarder as with the Linux allocator.
Quantifying the Performance of Garbage Collection vs. Explicit Memory ManagementEmery Berger
This talk answers an age-old question: is garbage collection faster/slower/the same speed as malloc/free? We introduce oracular memory management, an approach that lets us measure unaltered Java programs as if they used malloc and free. The result: a good GC can match the performance of a good allocator, but it takes 5X more space. If physical memory is tight, however, conventional garbage collectors suffer an order-of-magnitude performance penalty.
Introduces bookmarking collection, a GC algorithm that works with the virtual memory manager to eliminate paging. Just before memory is paged out, the collector "bookmarks" the targets of pointers from the pages. Using these bookmarks, BC can perform full garbage collections without loading the pages back from disk. By performing in-memory garbage collections, BC can speed up Java programs by orders of magnitude (up to 41X).
DieHard: Probabilistic Memory Safety for Unsafe LanguagesEmery Berger
DieHard uses randomization and replication to transparently make C and C++ programs tolerate a wide range of errors, including buffer overflows and dangling pointers. Instead of crashing or running amok, DieHard lets programs continue to run correctly in the face of memory errors with high probability. Using DieHard also makes programs highly resistant to heap-based hacker attacks. Downloadable at www.diehard-software.org.
Exterminator: Automatically Correcting Memory Errors with High ProbabilityEmery Berger
Exterminator automatically corrects heap-based memory errors without programmer intervention. It exploits randomization and replication (or multiple users) to pinpoint errors with high precision. From this information, Exterminator derives runtime patches that fix these errors in current and subsequent executions.
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
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/
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.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
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/
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.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
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.
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.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
Operating Systems - Advanced Synchronization
1. Operating Systems
CMPSCI 377
Advanced Synchronization
Emery Berger
University of Massachusetts Amherst
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science
2. Why Synchronization?
Synchronization serves two purposes:
Ensure safety for shared updates
Avoid race conditions
Coordinate actions of threads
Parallel computation
Event notification
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 2
3. Synch. Operations
Safety:
Locks
Coordination:
Semaphores
Condition variables
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 3
4. Safety
Multiple threads/processes – access shared
resource simultaneously
Safe only if:
All accesses have no effect on resource,
e.g., reading a variable, or
All accesses idempotent
E.g., a = abs(x), a = highbit(a)
Only one access at a time:
mutual exclusion
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 4
5. Safety: Example
“The too much milk problem”
Model of need to synchronize activities
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 5
6. Why You Need Locks
thread A thread B
if (no milk && no note) if (no milk && no note)
leave note leave note
buy milk buy milk
remove note remove note
Does this work? milk
too much
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 6
7. Mutual Exclusion
Prevent more than one thread from
accessing critical section
Serializes access to section
Lock, update, unlock:
lock (&l);
update data; /* critical section */
unlock (&l);
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 7
8. Too Much Milk: Locks
thread A thread B
lock(&l) lock(&l)
if (no milk) if (no milk)
buy milk buy milk
unlock(&l) unlock(&l)
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 8
9. Exercise!
Simple multi-threaded program
N = number of iterations
Spawn that many threads to compute
expensiveComputation(i)
Add value (safely!) to total
Use:
pthread_mutex_create, _lock, _unlock
pthread_mutex_t myLock;
pthread_create, pthread_join
pthread_t threads[100];
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 9
11. Solution
#include <pthread.h>
int main (int argc, char * argv[]) {
int total = 0;
int n = atoi(argv[1]);
pthread_mutex_t lock;
// mutex init
void * wrapper (void * x) {
pthread_mutex_init (&lock);
int v = *((int *) x); // allocate threads
delete ((int *) x); pthread_t * threads = new pthread_t[n];
// spawn threads
int res = expComp (v);
for (int i = 0; i<n; i++) {
pthread_mutex_lock (&lock);
// heap allocate args
total += res;
int * newI = new int;
pthread_mutex_unlock (&lock); *newI = i;
return NULL; pthread_create (&threads[i], wrapper,
(void *) newI);
}
}
// join
for (int i = 0; i<n; i++) {
pthread_join (threads[i], NULL);
}
// done
printf (“total = %dn”, total);
return 0;
}
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 11
12. Atomic Operations
But: locks are also variables, updated
concurrently by multiple threads
Lock the lock?
Answer: use hardware-level atomic
operations
Test-and-set
Compare-and-swap
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 12
13. Test&Set Semantics
int testAndset (int& v) {
int old = v;
v = 1;
return old;
}
pseudo-code: red = atomic
What’s the effect of
testAndset(value)
when:
value = 0?
(“unlocked”)
value = 1?
(“locked”)
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 13
14. Lock Variants
Blocking Locks
Spin locks
Hybrids
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 14
15. Blocking Locks
Suspend thread immediately
Lets scheduler execute another thread
Minimizes time spent waiting
But: always causes context switch
void blockinglock (Lock& l) {
while (testAndSet(l.v) == 1) {
sched_yield();
}
}
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 15
16. Spin Locks
Instead of blocking, loop until lock released
void spinlock (Lock& l) {
while (testAndSet(l.v) == 1) {
;
}
}
void spinlock2 (Lock& l) {
while (testAndSet(l.v) == 1) {
while (l.v == 1)
;
}
}
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 16
17. Other Variants
Spin-then-yield:
Spin for some time, then yield
Fixed spin time
Exponential backoff
Queuing locks, etc.:
Ensure fairness and scalability
Major research issue in 90’s
Not used (much) in real systems
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 17
18. “Safety”
Locks can enforce mutual exclusion,
but notorious source of errors
Failure to unlock
Double locking
Deadlock
Priority inversion
not an “error” per se
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 18
19. Failure to Unlock
pthread_mutex_t l;
void square (void) {
pthread_mutex_lock (&l);
// acquires lock
// do stuff
if (x == 0) {
return;
} else {
x = x * x;
}
pthread_mutex_unlock (&l);
}
What happens when we call square()
twice when x == 0?
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 19
20. Scoped Locks with RAI
Scoped Locks:
acquired on entry, released on exit
C++: Resource Acquisition is Initialization
class Guard {
public:
Guard (pthread_mutex_t& l)
: _lock (l)
{ pthread_mutex_lock (&_lock);}
~Guard (void) {
pthread_mutex_unlock (&_lock);
}
private:
pthread_mutex_t& _lock;
};
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 20
21. Scoped Locks: Usage
Prevents failure to unlock
pthread_mutex_t l;
void square (void) {
Guard lockIt (&l);
// acquires lock
// do stuff
if (x == 0) {
return; // releases lock
} else {
x = x * x;
}
// releases lock
}
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 21
22. Double-Locking
Another common mistake
pthread_mutex_lock (&l);
// do stuff
// now unlock (or not...)
pthread_mutex_lock (&l);
Now what?
Can find with static checkers –
numerous instances in Linux kernel
Better: avoid problem
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 22
23. Recursive Locks
Solution: recursive locks
If unlocked:
threadID = pthread_self()
count = 1
Same thread locks increment count
Otherwise, block
Unlock decrement count
Really unlock when count == 0
Default in Java, optional in POSIX
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 23
24. Increasing Concurrency
One object, shared among threads
W R R W R
Each thread is either a reader or a writer
Readers – only read data, never modify
Writers – read & modify data
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 24
25. Single Lock Solution
thread A thread B thread C
lock(&l) lock(&l) lock(&l)
Read data Modify data Read data
unlock(&l) unlock(&l) unlock(&l)
thread D thread E thread F
lock(&l) lock(&l) lock(&l)
Read data Read data Modify data
unlock(&l) unlock(&l) unlock(&l)
Drawbacks of this solution?
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 25
26. Optimization
Single lock: safe, but limits
concurrency
Only one thread at a time, but…
Safe to have simultaneous readers
Must guarantee mutual exclusion for
writers
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 26
27. Readers/Writers
thread A thread B thread C
rlock(&rw) wlock(&rw) rlock(&rw)
Read data Modify data Read data
unlock(&rw) unlock(&rw) unlock(&rw)
thread D thread E thread F
rlock(&rw) rlock(&rw) wlock(&rw)
Read data Read data Modify data
unlock(&rw) unlock(&rw) unlock(&rw)
Maximizes concurrency
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 27
28. R/W Locks – Issues
When readers and writers both queued up,
who gets lock?
Favor readers
Improves concurrency
Can starve writers
Favor writers
Alternate
Avoids starvation
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 28
29. Synch. Operations
Safety:
Locks
Coordination:
Semaphores
Condition variables
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 29
30. Semaphores
What’s a “semaphore” anyway?
A visual signaling
apparatus with
flags, lights, or
mechanically
moving arms, as
one used on a
railroad.
Regulates traffic at critical section
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 30
31. Semaphores in CS
Computer science: Dijkstra (1965)
A non-negative
integer counter with
atomic increment &
decrement.
Blocks rather than
going negative.
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 31
32. Semaphore Operations
P(sem), a.k.a. wait = V(sem), a.k.a. signal =
decrement counter increment counter
If sem = 0, block until Wake 1 waiting process
greater than zero V = “verhogen”
P = “prolagen” (proberen (“increase”)
te verlagen, “try to
decrease”)
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 32
33. Semaphore Example
More flexible than locks
By initializing semaphore to 0,
threads can wait for an event to occur
thread A thread B
// wait for thread B // do stuff, then
// wake up A
sem.wait();
sem.signal();
// do stuff …
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 33
34. Counting Semaphores
Controlling resources:
E.g., allow threads to use at most 5 files
simultaneously
Initialize to 5
thread A thread B
sem.wait(); sem.wait();
// use a file // use a file
sem.signal(); sem.signal();
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 34
35. Synch Problem: Queue
Suppose we have a thread-safe queue
insert(item), remove()
Options for remove when queue empty:
Return special error value (e.g., NULL)
Throw an exception
Wait for something to appear in the queue
Wait = sleep()
But sleep when holding lock…
Goes to sleep
Never wakes up!
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 35
36. Condition Variables
Wait for 1 event, atomically grab lock
wait(Lock& l)
If queue is empty, wait
Atomically releases lock, goes to sleep
Reacquires lock when awakened
notify()
Insert item in queue
Wakes up one waiting thread, if any
notifyAll()
Wakes up all waiting threads
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 36
37. Deadlock
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 37
38. Deadlocks
Deadlock = condition where two
threads/processes wait on each other
thread A thread B
printer->wait(); disk->wait();
disk->wait(); printer->wait();
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 38
39. Deadlocks, Example II
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 39
40. Deadlocks - Terminology
Deadlock
When several threads compete for finite number
of resources simultaneously
Deadlock prevention algorithms
Check resource requests & availability
Deadlock detection (rarely used today)
Finds instances of deadlock when threads stop
making progress
Tries to recover
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 40
41. Rules for Deadlock
All of below must hold:
Mutual exclusion:
1.
Resource used by one thread at a time
Hold and wait
2.
One thread holds resource while waiting for
another; other thread holds that resource
No preemption
3.
Thread can only release resource voluntarily
No other thread or OS can force thread to release
resource
Circular wait
4.
Set of threads {t1, …, tn}: ti waits on ti+1,
tn waits on t1
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 41
42. Circular Waiting
If no way to free resources (preemption),
deadlock
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 42
43. Deadlock Detection
Define graph with vertices:
Resources = {r1, …, rm}
Threads = {t1, …, tn}
Request edge from thread to resource
(rj → ti)
Assignment edge from resource to thread
(rj → ti)
OS has allocated resource to thread
Result:
No cycles no deadlock
Cycle may deadlock
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 43
44. Example
Deadlock or not?
Request edge from
thread to resource ti -> rj
Thread: requested
resource but not
acquired it
Assignment edge from
resource to thread rj -> ti
OS has allocated
resource to thread
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 44
45. Multiple Resources
What if there are multiple
interchangeable instances of a resource?
Cycle deadlock might exist
If any instance held by thread outside
cycle, progress possible when thread
releases resource
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 45
46. Deadlock Detection
Deadlock or not?
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 46
47. Exercise: Resource Allocation Graph
Draw a graph for the following event:
Request edge from thread
to resource ti -> rj
Thread: requested
resource but not
acquired it
Assignment edge from
resource to thread rj -> ti
OS has allocated
resource to thread
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 47
48. Resource Allocation Graph
Draw a graph for the following event:
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 48
49. Detecting Deadlock
Scan resource allocation graph
for cycles & break them!
Different ways to break cycles:
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 49
50. Detecting Deadlock
Scan resource allocation graph
for cycles & break them!
Different ways to break cycles:
Kill all threads in cycle
Kill threads one at a time
Force to give up resources
Preempt resources one at a time
Roll back thread state to before acquiring resource
Common in database transactions
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 50
51. Deadlock Prevention
Instead of detection, ensure at least one
of necessary conditions doesn’t hold
Mutual exclusion
Hold and wait
No preemption
Circular wait
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 51
52. Deadlock Prevention
Mutual exclusion
Make resources shareable (but not all
resources can be shared)
Hold and wait
Guarantee that thread cannot hold one
resource when it requests another
Make threads request all resources they
need at once and release all before
requesting new set
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 52
53. Deadlock Prevention, continued
No preemption
If thread requests resource that cannot be
immediately allocated to it
OS preempts (releases) all resources thread
currently holds
When all resources available:
OS restarts thread
Problem: not all resources can be
preempted
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 53
54. Deadlock Prevention, continued
Circular wait
Impose ordering (numbering) on resources
and request them in order
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 54
55. Avoiding Deadlock
Cycle in locking graph = deadlock
Standard solution:
canonical order for locks
Acquire in increasing order
E.g., lock_1, lock_2, lock_3
Release in decreasing order
Ensures deadlock-freedom,
but not always easy to do
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 55
56. The End
UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 56