多线程交替输出字符串(2)
与上一篇逻辑类似,这里采用同样的生产者消费者模式
创建线程使用了BlockOperation封装操作,使用OperationQueue作为并发队列
代码如下:
import Foundation var run: Bool = true /// 将字符转成UInt8 func charToInt(chr: Character) -> UInt8? { return chr.asciiValue } /// 将Uint8转成字符 func intToChr(asciiValue: UInt8) -> Character? { return Character(UnicodeScalar(asciiValue)) } /// 组 let group = DispatchGroup() group.enter() let queue = OperationQueue() queue.maxConcurrentOperationCount = 2 guard var start1: UInt8 = charToInt(chr: Character("A")) else { exit(-1) } let semaphore1 = DispatchSemaphore(value: 1) let semaphore2 = DispatchSemaphore(value: 0) let op1 = BlockOperation(block: { while run { sleep(1) semaphore1.wait() let first = (start1 - 65) % 26 + 65 start1 = start1 + 1 let second = (start1 - 65) % 26 + 65 start1 = start1 + 1 print("\(intToChr(asciiValue: first)!), \(intToChr(asciiValue: second)!)") semaphore2.signal() } group.leave() }) var start2 = 0 let op2 = BlockOperation(block: { while run { sleep(1) semaphore2.wait() print("\(start2 % 10)") start2 = start2 + 1 semaphore1.signal() } group.leave() }) queue.addOperation(op1) queue.addOperation(op2) group.wait()