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 12, grupa śr. 10-12, 17 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 | | ----------------------:| --- | --- | --- | --- | --- | --- | --- | Mikołaj Balwicki | X | X | X | X | | | | Konrad Kowalczyk | | X | X | | | | | Jakub Krzyżowski | X | X | X | X | | | | Łukasz Magnuszewski | | | | | | | | Marcin Majchrzyk | | X | X | X | | X | X | Jan Marek | | X | X | | | X | | Marcin Mierzejewski | | | | | | | | Juan Jose Nieto Ruiz | | | | | | | | Konrad Oleksy | | | | | | | | Javier Rábago Montero | X | X | X | X | X | | | Michał Mękarski | | X | X | | X | X | X | ::: :::info **Uwaga:** Po rozwiązaniu zadania należy zmienić kolor nagłówka na zielony. ::: ## Zadanie 1 :::success Autor: Jakub Krzyżowski ::: **Zadanie 1.** Rozważmy punkty linearyzacji metod enq() i deq() w kolejce LockFreeQueue. 1. Czy jako punkt linearyzacji metody deq(), w przypadku gdy odnosi ona sukces, można wybrać instrukcję która odczytuje zwracaną wartość z węzła? ```java= public T deq() throws EmptyException { while (true) { Node first = head.get(); Node last = tail.get(); Node next = first.next.get(); if (first == head.get()) { if (first == last) { if (next == null) { throw new EmptyException(); } tail.compareAndSet(last, next); } else { T value = next.value; if (head.compareAndSet(first, next)) { return value; } } } } } ``` Nie można. Punktem linearyzacji tej metody będzie zakończony powodzeniem `compareAndSet(first, next)`. Gdyby punktem linearyzacji było odczytanie wartości z węzła, to w żaden sposób nie zmieniamy stanu naszej struktury, a zatem inne wątki nie widzą efektów naszego działania pomimo tego, że wywołanie jest już zlinearyzowane, a więc efekty powinny być widoczne. 2. Czy jako punkt linearyzacji metody enq() można wybrać instrukcję (być może wykonywaną przez inny wątek), która z sukcesem aktualizuje pole tail? ```java= public void enq(T value) { Node node = new Node(value); while (true) { Node last = tail.get(); Node next = last.next.get(); if (last == tail.get()) { if (next == null) { if (last.next.compareAndSet(next, node)) { tail.compareAndSet(last, node); return; } } else { tail.compareAndSet(last, next); } } } } ``` Można wybrać taki punkt linearyzacji, bo po takiej instrukcji jest już zaktualizowany zarówno wskaźnik w poprzedniku, jak i pole last. Nie musi robić tego jednak wątek który wykonał `last.next.compareAndSet(next, node)`, mogą to robić inne, szybsze wątki działające współbieżnie z nim wykonujące `enq()` i `deq()`, które zauważą, że tail nie został nadal przepięty na nowy węzeł. ## Zadanie 2 :::success Autor: Konrad Kowalczyk ::: ![zad2l12](https://hackmd.io/_uploads/HyYdhGSt6.png) Problem ABA polega na zmianie referencji, na którą akurat patrzy wątek, z A na B i z powrotem na A. Wątek nie wykrył zmiany (referencja wciąż wskazuje na A) ale sytuacja wokół A mogła się znacząco zmienić. Problem ten objawia się między innymi w algorytmach używających instrukcji `compareAndSet()`. Przypuśćmy, że mamy kolejkę, a nieużywane węzły przechowujemy w listach poszczególnych wątków, aby móc wykorzystać je ponownie. Niech dana będzie taka sytuacja: - wątek 0, będący dequeuerem, patrzy na początek kolejki i widzi element A (strażnika) oraz następujący po nim element B - wątek 0 zostaje uśpiony - inny wątek ściąga element A z kolejki, a także element B - jeszcze inny wątek wkłada element A z powrotem do kolejki - wątek 0 wybudza się i aby sprawdzić poprawność swojej sytuacji, wykonuje `compareAndSet()` na początku kolejki - `compareAndSet()` zwraca `true`, ponieważ na początku kolejki znajduje się element A - wątek 0 przepina początek kolejki na element B, który obecnie znajduje się na liście węzłów nieużywanych Aby zapobiec problemowi ABA, można wykorzystać referencje z sygnaturami. Każdy węzeł posiada nie tylko referencję, ale także sygnaturę, która zostaje zmieniona za każdym razem, kiedy sam węzeł ulegnie modyfikacji (w tym również przeniesieniu). Instrukcja `compareAndSet()` w momencie wybudzenia się wątku 0 zobaczy inną sygnaturę i zwróci `false`, co zapobiegnie błędnemu przepięciu. W niektórych architekturach dostępne są również metody `load-linked/store-conditional`, które sprawdzają nie czy wartość jest taka sama w dwóch różnych momentach, tylko czy pomiędzy tymi momentami została w jakikolwiek sposób zmieniona. Jako że początek kolejki w problemie ABA zmienił się z A na B oraz z powrotem na A, metody te wykryją zmianę i nie pozwolą problemowi ABA wystąpić. ## Zadanie 3 :::success Autor: Javier Rábago Montero ::: ![z3](https://hackmd.io/_uploads/Hy87aMrYa.png) ![sync](https://hackmd.io/_uploads/BkIG6MHYp.png) The class has four instance variables, item, that stores the item to be queued or dequeued, boolean queue to indicate whether an item is being enqueued, and lock and condition for synchronization. Method enq() first takes the lock and checks if enqueuing is true, if so it waits using condition.await(). Once it is, it set enqueuing to true and updates the item variable. It then signals all waiting threads using condition.signalAll(). It waits until the item is dequeued using another while loop and condition.await(). Finally it sets enqueuing to false and signals all waiting threads. The deq() method takes the lock and waits while item is null if the queue is empty for the moment. Once an item is available it sets it to null, signals all waiting threads and returns the dequeued item. The lock is finally released. The queue is implemented as a list of nodes. In this example, we can take a thread that runs enq() as producer, and one that runs deq() as consumer. In synchronous data structures like this, a producer puts an item in the queue block until it is removed by a consumer. This action is called a rendezvous, where enq() works synchronized with deq(), the first passes the first to the second. ## Zadanie 4 :::success Autor: Mikołaj Balwicki ::: ![image](https://hackmd.io/_uploads/B1gkTMHK6.png) ![image](https://hackmd.io/_uploads/By5MaMBFp.png) ## Zadanie 5 :::success Autor: Michał Mękarski ::: ![image](https://hackmd.io/_uploads/BkeF9QBtT.png) ![image](https://hackmd.io/_uploads/rJepcXHYp.png) ![image](https://hackmd.io/_uploads/SkMCiXBKa.png) ### Figure 11.10 ![image](https://hackmd.io/_uploads/rkyuomHFa.png) ### Problematyczny moment ![image](https://hackmd.io/_uploads/BJdvpmSFa.png) ### Rozwiązanie ![image](https://hackmd.io/_uploads/B1zK0mSt6.png) ![image](https://hackmd.io/_uploads/HJIFBNBYa.png) ## Zadanie 6 :::success Autor: Jan Marek ::: ![image](https://hackmd.io/_uploads/r1A4pMHK6.png) ![image](https://hackmd.io/_uploads/BJ9FpMHYT.png) Przykładowo: 2 wątki (A, B), pusta tablica `items`. 1. Wątek A wykonuje metodę `push()`. Wykona `top.getAndIncrement()` i idzie spać. Czyli teraz `top == 1`. 2. Wątek B wykonuje całą metodę `pop()`, czyli zwróci na koniec `items[0]`, ale A nie zdążył jeszcze niczego tam umieścić. ```java= public class Stack<T> { private AtomicInteger top; private T[] items; private Rooms rooms; public Stack(int capacity) { top = new AtomicInteger(); items = (T[]) new Object[capacity]; rooms = new Rooms(2); } public void push(T x) throws FullException { rooms.enter(0); int i = top.getAndIncrement(); if (i >= items.length) { top.getAndDecrement(); rooms.exit(); throw new FullException(); } items[i] = x; rooms.exit(); } public T pop() throws EmptyException { rooms.enter(1); int i = top.getAndDecrement() - 1; if (i < 0) { top.getAndIncrement(); rooms.exit(); throw new EmptyException(); } T item = items[i]; rooms.exit(); return item; } } ``` ## Zadanie 7 :::success Autor: Marcin Majchrzyk ::: ``` java= public void push(T x) { while (true) { if (isFull) continue; rooms.enter(0); int i = top.getAndIncrement(); if (i >= items.length) { top.getAndDecrement(); isFull = true; rooms.exit(); continue; } items[i] = x; rooms.exit(); return; } } void onEmpty() { if (!isFull) return; T[] newItems = new T[items.length + 1]; System.arrayCopy(items, 0, newItems, 0, items.length); items = newItems; isFull = false; } ```

    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