Skip to content

Instantly share code, notes, and snippets.

@menangen
Last active April 4, 2021 08:00
Show Gist options
  • Save menangen/7b7035ea0a4a0d06b0298e219dcdadfa to your computer and use it in GitHub Desktop.
Save menangen/7b7035ea0a4a0d06b0298e219dcdadfa to your computer and use it in GitHub Desktop.
Swift 4.0 Multiprocessing
//
// main.swift
// Multithreading
//
// Created by menangen on 16/01/2019.
// Copyright © 2019 menangen. All rights reserved.
//
import Foundation
var udpArray: [String] = ["Packet1", "Packet2", "Packet3"]
var thread1Buffer: [String] = []
let operationLoopQueue = OperationQueue()
let udpQueue = OperationQueue()
let bufferSemaphore = DispatchSemaphore(value: 1)
let runLoopSemaphore = DispatchSemaphore(value: 0)
let runLoopBlock = BlockOperation {
print("Enter Block A")
var el: String
while true {
runLoopSemaphore.wait()
bufferSemaphore.wait()
el = thread1Buffer.popLast() ?? "NULL"
bufferSemaphore.signal()
print("\t Processing |\(el)|", Thread.current)
sleep(3)
bufferSemaphore.wait()
if (thread1Buffer.count == 0) { break }
bufferSemaphore.signal()
}
}
udpQueue.addOperation({
for el in udpArray {
sleep(1)
bufferSemaphore.wait()
thread1Buffer.append(el); print("Sending \(el) to Thread", Thread.current)
runLoopSemaphore.signal()
bufferSemaphore.signal()
}
})
operationLoopQueue.addOperations([runLoopBlock], waitUntilFinished: true)
print("thread1Buffer on END: ", thread1Buffer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment