Skip to content

Instantly share code, notes, and snippets.

@wotjd
Created September 21, 2018 10:17
Show Gist options
  • Save wotjd/07a894022c5e1d3a68f663797a893b53 to your computer and use it in GitHub Desktop.
Save wotjd/07a894022c5e1d3a68f663797a893b53 to your computer and use it in GitHub Desktop.
test dispatch queue, dispatch semaphore, ...
import UIKit
import Foundation
let queue = DispatchQueue(label: "wotjd", attributes: .concurrent)
func sendMessage(str: String, pendingTime: UInt32, completion: @escaping () -> Void) {
queue.async {
sleep(pendingTime)
print(str)
completion()
}
}
let pendingStart:DispatchSemaphore = DispatchSemaphore(value: 0)
let pendingUpload:DispatchSemaphore = DispatchSemaphore(value: 0)
let startUpload = DispatchWorkItem {
sendMessage(str: "upload started!", pendingTime: 2) {
print("started")
pendingStart.signal()
}
}
let uploadInfo = DispatchWorkItem {
pendingStart.wait()
sendMessage(str: "Info uploaded!", pendingTime: 1) {
print("uploaded")
pendingUpload.signal()
}
}
var isRunning = true
let dataQueue = DispatchQueue(label: "wotjd_data")
var data = [Int]()
var valueSum = 0
var ESCounter = 0
let sendES = DispatchWorkItem {
valueSum = 0
dataQueue.sync() {
if !data.isEmpty {
for i in 0..<data.endIndex {//stride(from: endIndex - 1, through: 0, by: -1) {
isRunning = data[i] != 499 // end loop trigger
valueSum += data[i]
}
data.removeAll()
}
}
if valueSum != 0 {
pendingUpload.wait()
sendMessage(str: "[ES:\(valueSum)] uploaded!", pendingTime: 1) {
print("uploaded")
ESCounter += 1
pendingUpload.signal()
}
}
}
//queue.sync(execute: startUpload)
//queue.sync(execute: uploadInfo)
startUpload.perform()
uploadInfo.perform()
let jobQueue = DispatchQueue(label: "wotjd_job", attributes: .concurrent)
jobQueue.async {
var a = 0;
for value in 0..<500 {
dataQueue.async() {
data.append(value)
}
a += value
}
print("sum result = \(a)")
}
//sleep(1)
//sendES.perform()
while isRunning {
sendES.perform()
}
var str = "Hello, playground"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment