Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

🧵 thread - Çok İş Parçacıklı Programlama

Thread, Mutex, Channel, Arc, Atomic, ThreadPool

67
Fonksiyon
878
Satır
27 KB
Boyut

🚀 Hızlı Başlangıç

içe_aktar thread

// Thread spawn
değişken handle = thread.spawn(fonksiyon() yap
    yazdır("Thread'den merhaba!")
    dön 42
son)

değişken sonuç = thread.join(handle)
yazdır("Sonuç: " + sonuç.yazıya())

// Mutex (mutual exclusion)
değişken sayaç = thread.mutex_new(0)

değişken threads = []
her i içinde aralık(0, 10) için yap
    threads.ekle(thread.spawn(fonksiyon() yap
        her j içinde aralık(0, 100) için yap
            thread.mutex_lock(sayaç, fonksiyon(değer) yap
                dön değer + 1
            son)
        son
    son))
son

her t içinde threads için yap
    thread.join(t)
son

değişken toplam = thread.mutex_get(sayaç)
yazdır("Toplam: " + toplam.yazıya())  // 1000

// Channel (message passing)
değişken (tx, rx) = thread.channel_create()

thread.spawn(fonksiyon() yap
    thread.channel_send(tx, "Mesaj 1")
    thread.channel_send(tx, "Mesaj 2")
son)

yazdır(thread.channel_receive(rx))  // "Mesaj 1"
yazdır(thread.channel_receive(rx))  // "Mesaj 2"

📚 Senkronizasyon

  • Mutex: Mutual exclusion lock
  • RwLock: Read-write lock (multiple readers, single writer)
  • Channel: Message passing (mpsc, mpmc)
  • Atomic: Lock-free atomic operations
  • Arc: Atomic reference counting
  • Barrier: Wait for all threads
  • Semaphore: Resource counting

💡 Örnekler

Producer-Consumer Pattern

içe_aktar thread, collections

değişken (tx, rx) = thread.channel_create()

// Producers
her i içinde aralık(0, 3) için yap
    değişken sender = tx.clone()
    thread.spawn(fonksiyon() yap
        her j içinde aralık(0, 5) için yap
            değişken mesaj = "Producer " + i.yazıya() + " - Item " + j.yazıya()
            thread.channel_send(sender, mesaj)
            thread.sleep(100)  // 100ms
        son
    son)
son

// Consumer
değişken consumer = thread.spawn(fonksiyon() yap
    değişken items = []
    
    döngü yap
        değişken sonuç = thread.channel_receive_timeout(rx, 1000)
        
        eğer sonuç.tamam_mı() ise yap
            değişken mesaj = sonuç.çıkar()
            yazdır("Tüketildi: " + mesaj)
            items.ekle(mesaj)
        son değilse yap
            // Timeout - tüm producer'lar bitmiş
            kır
        son
    son
    
    dön items.uzunluk()
son)

değişken toplam = thread.join(consumer)
yazdır("Toplam item: " + toplam.yazıya())  // 15

← fs | sys →