CS计算机代考程序代写 Java concurrency data structure For the rest of the session…

For the rest of the session…

Functional Concurrency

To review…
We can write concurrent code with threads

Definitions
Concurrency: A program is concurrent if it may have more than one active execution context, i.e. more than one “thread of control”
Thread: An independent pathway of code execution
Parallelism: A concurrent program is “parallel” if more than one task is physically active at once; this requires more than one processor.

To review…
In imperative languages, it’s possible for 2+ threads to mutate the same variable in shared memory, which can lead to a race condition
Definition
Race condition: The main source of complexity in an imperative concurrent program. A race condition occurs whenever two or more threads are “racing” towards points in the code at which they touch some common object, and the behavior of the system depends on which thread gets there first.

To review…
Race conditions are annoying: they’re hard to replicate and you have to solve them by, for example, synchronizing threads’ access to methods that mutate state, or by using Atomic variables whose methods can’t be interrupted
Functional programming by definition doesn’t have this problem, and therefore needs no solution to it. No mutable state, so no race condition, so no need to synchronize/use atomic classes. Just set up your threads.

Last Session:
“Top Three Words” Program in Racket
(define (mapToLowercase ls)
(map string-downcase ls))

(define (sortListAlphab ls)
(sort ls string (car(cdr x)) (car (cdr y))))

(define (takeTop3 ls)
(take ls 3))

(define (find3MostFreqWds ls)
(takeTop3 (sortListDescFreq (frequencyLs (sortListAlphab (mapToLowercase ls))))))

How would we solve the same problem imperatively? (let’s use Java)
Use a HashMap data structure
Key: the word
Value: the number of times it appears
Iterate over our list of words; if the word is already in our HashMap, increment its key; otherwise, put the word in the HashMap with a value of 1.
Find top 3: iterate over the HashMap and find the max three times

Simple threads in Racket

Output on two occasions

Threading Top3Words.rkt
Things to think about:
Which parts of the program can be run simultaneously?
How should the main thread evaluate the information that comes back from the two other threads?
Things not to worry about:
Race conditions

Participation Quiz

/docProps/thumbnail.jpeg

Leave a Reply

Your email address will not be published. Required fields are marked *