Dydaktyka
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Ćwiczenia 13, grupa cz. 16-18, 18 stycznia 2024 ###### tags: `PRW23` `ćwiczenia` `pwit` ## Deklaracje Gotowość rozwiązania zadania należy wyrazić poprzez postawienie X w odpowiedniej kolumnie! Jeśli pożądasz zreferować dane zadanie (co najwyżej jedno!) w trakcie dyskusji oznacz je znakiem ==X== na żółtym tle. **UWAGA: Tabelkę wolno edytować tylko wtedy, gdy jest na zielonym tle!** :::danger | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | | ----------------------:| ----- | --- | --- | --- | --- | --- | --- | Dominik Baziuk | | | | | | | | Paweł Borek | | | | | | | | Arti Brzozowski | | | | | | | | Mateusz Golisz | | | | | | | | Kacper Jóźwiak | | | | | | | | Julia Konefał | | | | | | | | Adam Korta | x | | | | | | | Jakub Mikołajczyk | X | | X | X | | | | Bartosz Morasz | x | | x | | | | | Andrzej Morawski | x | x | x | | | | | Aleksandra Nicpoń | x | x | x | | | | | Mateusz Reis | x | | x | | | | | Tomasz Stachurski | X | | X | | | | | Marcel Szelwiga | X | X | X | | | | | Volha Tsekalo | x | x | | | | | | Martyna Wybraniec | x | x | x | | | | | Denys Zinoviev | | | | | | | | Dominik Olejarz | x | | x | | | | | ::: Tutaj można zadeklarować zaległe zadania 1 i 4 z listy 12: :::danger | | 12.1 | 12.4 | | ----------------------:| ----- | ----- | | Tomasz Stachurski | | X | | Marcel Szelwiga | X | X | | Andrzej Morawski | X | | | | | | ::: :::info **Uwaga:** Po rozwiązaniu zadania należy zmienić kolor nagłówka na zielony. ::: ## Zadanie 1 :::success Autor: Bartosz Morasz ::: ![image](https://hackmd.io/_uploads/HkpDOiIFT.png) ![image](https://hackmd.io/_uploads/rJdwGsUK6.png) ## Zadanie 2 :::success Autor: Martyna Wybraniec ::: ![image](https://hackmd.io/_uploads/Hk1T6uUKa.png) ![image](https://hackmd.io/_uploads/rJp_VtLKa.png) ![image](https://hackmd.io/_uploads/r1uV8Y8YT.png) ![image](https://hackmd.io/_uploads/r14BIYLt6.png) Klasa `RangePolicy` odpowiada za dynamiczne ustawianie przedziału, z którego wątek losuje komórkę EliminationArray. Jeśli zauważa dużo timeoutów, zmniejsza zakres i odwrotnie. Punkty linearyzacji: - jeśli metoda `push()` lub `pop()` zmodyfikowała `LockFreeStack` punktem linearyzacji będzie miejsce uzyskania dostępu do stosu - jeśli doszło do eliminacji punkt linearyzacji to moment wymiany ## Zadanie 3 :::success Autor: Marcel Szelwiga ::: ``` ----[ ]---- | | [ ] [ ] / \ / \ () () () () ``` ```java= public int getAndIncrement() { Stack<Node> stack = new Stack<Node>(); Node myLeaf = leaf[ThreadID.get()/2]; Node node = myLeaf; // precombining phase while (node.precombine()) { node = node.parent; } Node stop = node; // combining phase int combined = 1; for (node = myLeaf; node != stop; node = node.parent) { combined = node.combine(combined); stack.push(node); } // operation phase int prior = stop.op(combined); // distribution phase while (!stack.empty()) { node = stack.pop(); node.distribute(prior); } return prior; } ``` Faza `precombination` -- każdy wątek zaczyna od swojego liścia i idzie do korzenia, kończy swoją drogę jeśli trafi do jakiegoś wierzchołka jako drugi. Jeśli dojdzie do korzenia, to znaczy, że to on będzie inkrementował globalny licznik. Natomiast jeśli dotrze jako drugi to w późniejszych etapach dostanie on od innego wierzchołka policzoną już dla niego wartość. Jeśli wątek był pierwszy to będzie musiał zebrać wartości od wątków drugich i przekazać je odpowiednio wyżej, do wierzchołka, w którym on był drugi lub korzenia. Faza `combination` -- w tej fazie wąkti idą do góry od liścia do korzenia i jeśli był pierwszy to zbiera wartość od swojego sąsiada i propaguje ją do góry. Wątek musi czekać na ten drugi. Tak całe drzewo, a w zasadzie cała używana część drzewa zostanie obsłużona przez jakiś wątek. Faza `operation` -- w tej fazie wątki, które czekały na poinformowanie o stanie licznika są budzone oraz dowiadują się jaka jest ich wartość, muszą wtedy tą wartość rozpropagować w swoim poddrzewie. Faza `distribution` -- w tej fazie wątek propaguje wartość na swoje poddrzewo. ## Zadanie 4 :::success Autor: Jakub Mikołajczyk ::: ![image](https://hackmd.io/_uploads/S1MiBAIKT.png) ![image](https://hackmd.io/_uploads/SyWhBRLYp.png) ![image](https://hackmd.io/_uploads/SJkTH08Kp.png) ![image](https://hackmd.io/_uploads/ByaaSCLYa.png) ![image](https://hackmd.io/_uploads/SyKAHA8tp.png) 1. ```precombine()``` - wolniejszy wątek przyszedł do węzła w momencie, gdy szybszy jest już w fazie ```combine``` i minął nasz wierzchołem ```combine()``` - szybszy wątek czeka aż wolniejszy wątek policzy swoje podrzewo 2. Ponieważ wywołanie ```op()``` i ```distibute()``` następuje po fazie ```combine```, zatem działają już na zablokowanych drzewach 3. ```precombine()``` - jeśli jesteśmy wolniejszym wątkiem to blokujemy szybszy wątek do momentu wyliczenia naszego podrzewa ```combine()``` - blokujemy spóźnione wątki ```op()``` - budzimy szybszy wątek czekający w ```combine```, gdy obliczyliśmy nasze podrzewo. Szybszy wątek w fazie ```distribute``` policzył rezultat i zrzucił na nas odpowiedzialność za wyzerowanie ustawień wierzchołka ```distribute()``` - jeśli nie było innego wątka to zerujemy ustawienia, w przeciwnym zrzucamy odpowiedzialność na wolniejszy wątek. ## Zadanie 5 :::success Autor: Jakub Mikołajczyk ::: ``` java= package z5; import java.util.Stack; public class TriCombiningTree { TriNode[] leaf; public TriCombiningTree(int width) { TriNode[] nodes = new TriNode[width + width / 2]; nodes[0] = new TriNode(); for (int i = 1; i < nodes.length; i++) { nodes[i] = new TriNode(nodes[(i - 1) / 3]); } leaf = new TriNode[width]; for (int i = 0; i < leaf.length; i++) { leaf[i] = nodes[nodes.length - i - 1]; } } public int getAndIncrement(int ThreadID) throws Exception { Stack<TriNode> stack = new Stack<>(); TriNode myLeaf = leaf[ThreadID/3]; TriNode node = myLeaf; // precombining phase while (node.precombine()) { node = node.parent; } TriNode stop = node; // combining phase int combined = 1; for (node = myLeaf; node != stop; node = node.parent) { combined = node.combine(combined); stack.push(node); } // operation phase int prior = stop.op(combined); // distribution phase while (!stack.empty()) { node = stack.pop(); node.distribute(prior); } return prior; } } ``` ```java= package z5; public class TriNode { enum CStatus {IDLE, FIRST, SECOND, THIRD, RESULT, ROOT;} CStatus cStatus; boolean lateLock; boolean waitLock; int waitingNodes, readyNodes; int firstValue; int[] secondVal = new int[2]; int[] result = new int[2]; TriNode parent; TriNode() { cStatus = CStatus.ROOT; lateLock = false; waitLock = false; waitingNodes = 0; readyNodes = 0; } TriNode(TriNode myParent) { parent = myParent; cStatus = CStatus.IDLE; lateLock = false; waitLock = false; waitingNodes = 0; readyNodes = 0; } synchronized boolean precombine() throws Exception { while (lateLock || waitingNodes >= 2) wait(); switch (cStatus) { case IDLE: cStatus = CStatus.FIRST; return true; case FIRST: waitLock = true; waitingNodes = 1; cStatus = CStatus.SECOND; return false; case SECOND: waitingNodes = 2; cStatus = CStatus.THIRD; return false; case ROOT: return false; default: throw new IllegalStateException("unexpected Node state " + cStatus); } } synchronized int combine(int combined) throws InterruptedException { while (waitLock || readyNodes < waitingNodes) wait(); firstValue = combined; lateLock = true; switch (cStatus) { case FIRST: return firstValue; case SECOND: return firstValue + secondVal[0]; case THIRD: return firstValue + secondVal[0] + secondVal[1]; default: throw new IllegalStateException("unexpected Node state " + cStatus); } } synchronized int op(int combined) throws InterruptedException, IllegalStateException { switch (cStatus) { case ROOT: int prior = result[0]; result[0] += combined; return prior; case SECOND: case THIRD: secondVal[readyNodes] = combined; readyNodes++; if (readyNodes == waitingNodes) { waitLock = false; notifyAll(); } while (cStatus != CStatus.RESULT) wait(); readyNodes--; prior = result[readyNodes]; if (readyNodes == 0) { lateLock = false; waitingNodes = 0; notifyAll(); cStatus = CStatus.IDLE; } return prior; default: throw new IllegalStateException("unexpected Node state " + cStatus); } } synchronized void distribute(int prior) { switch (cStatus) { case FIRST: cStatus = CStatus.IDLE; lateLock = false; break; case SECOND: result[0] = prior + firstValue; cStatus = CStatus.RESULT; break; case THIRD: result[1] = prior + firstValue; result[0] = result[1] + secondVal[0]; cStatus = CStatus.RESULT; break; default: throw new IllegalStateException("unexpected Node state " + cStatus); } notifyAll(); } } ``` ## Zadanie 6 :::success Autor: Jakub Mikołajczyk ::: ```java= package z6; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class ExchangeNode { enum CStatus {IDLE, FIRST, SECOND, ROOT;} CStatus cStatus; boolean lock; int firstValue; LockFreeExchanger<Integer> exchanger; ExchangeNode parent; ExchangeNode() { cStatus = CStatus.ROOT; lock = false; } ExchangeNode(ExchangeNode myParent) { parent = myParent; cStatus = CStatus.IDLE; lock = false; exchanger = new LockFreeExchanger<Integer>(); } synchronized boolean precombine() throws Exception { while (lock) wait(); switch (cStatus) { case IDLE: cStatus = CStatus.FIRST; return true; case FIRST: lock = true; cStatus = CStatus.SECOND; return false; case ROOT: return false; default: throw new IllegalStateException("unexpected Node state " + cStatus); } } synchronized int combine(int combined) throws InterruptedException, TimeoutException { lock = true; firstValue = combined; switch (cStatus) { case FIRST: return firstValue; case SECOND: return firstValue + exchanger.exchange(0, 10, TimeUnit.SECONDS); default: throw new IllegalStateException("unexpected Node state " + cStatus); } } synchronized int op(int combined) throws InterruptedException, IllegalStateException, TimeoutException { switch (cStatus) { case ROOT: int prior = firstValue; firstValue += combined; return prior; case SECOND: exchanger.exchange(combined, 10, TimeUnit.SECONDS); int result = exchanger.exchange(0, 10, TimeUnit.SECONDS); cStatus = CStatus.IDLE; lock = false; return result; default: throw new IllegalStateException("unexpected Node state " + cStatus); } } synchronized void distribute(int prior) throws InterruptedException, TimeoutException { switch (cStatus) { case FIRST: cStatus = CStatus.IDLE; lock = false; break; case SECOND: exchanger.exchange(firstValue + prior, 10, TimeUnit.SECONDS); break; default: throw new IllegalStateException("unexpected Node state " + cStatus); } notifyAll(); } } ``` ## Zadanie 7 :::success Autor: Jakub Mikołajczyk ::: ```java= package z7; import z5.TriCombiningTree; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.ReentrantLock; public class Pool<T> { TriCombiningTree in, out; List<T> pool; ReentrantLock[] locks; Pool(int poolSize, int threadsNum){ in = new TriCombiningTree(Math.ceilDiv(threadsNum, 3)); out = new TriCombiningTree(Math.ceilDiv(threadsNum, 3)); locks = new ReentrantLock[poolSize]; pool = new ArrayList<>(poolSize); for (int i = 0; i < poolSize; i++) { pool.add(null); locks[i] = new ReentrantLock(); } } void put(T item, int threadId) throws Exception { int i = in.getAndIncrement(threadId) % pool.size(); while (true) { while (!locks[i].tryLock()) ; try { if (pool.get(i) == null) { pool.set(i, item); System.out.println("THREAT ID: " + threadId + " PUT: " + item); return; } } finally { locks[i].unlock(); } } } T get (int threadId) throws Exception { int i = out.getAndIncrement(threadId) % pool.size(); while (true) { while (!locks[i].tryLock()) ; try { if (pool.get(i) != null) { System.out.println("THREAT ID: " + threadId + " GET: " + pool.get(i)); return pool.set(i, null); } } finally { locks[i].unlock(); } } } } ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully