块没有真正执行?

时间:2015-11-07 18:41:23

标签: swift locking closures nsthread

我试图使用NSThread的子类来运行一些命令。在您推荐NSOperation或GCD之前,我需要使用线程。

下面是我的代码和输出。正在创建块并将其添加到数组中,并且据说正在被线程出列并运行,但是我没有看到由于块的运行而产生的任何输出。为什么不呢?

import UIKit

class ViewController: UIViewController {

    private let _queue = dispatch_queue_create("com.AaronLBratcher.ALBQueue", nil)
    private let _thread = TestThread()
    private let _lock = NSCondition()

    override func viewDidLoad() {
        super.viewDidLoad()

        _thread.start()

        var openSuccessful = false

        dispatch_sync(_queue) {[unowned self] () -> Void in
            self._lock.lock()
            self._thread.openFile("file path here", completion: { (successful) -> Void in
                print("completion block running...")
                openSuccessful = successful
                self._lock.signal()
                self._lock.unlock()
            })
            self._lock.wait()
        }

        print("open operation complete")
        print(openSuccessful)
    }


    final class TestThread:NSThread {
        var _iterations = 0
        var _lock = NSCondition()
        var _blocks = [Any]()

        func openFile(FilePath:String, completion:(successful:Bool) -> Void) {
            print("queueing openFile...")

            let block = {[unowned self] in
                self._iterations = self._iterations + 1
                print("opening file...")
                completion(successful: true)
            }

            addBlock(block)
        }

        func addBlock(block:Any) {
            _lock.lock()
            _blocks.append(block)
            _lock.signal()
            _lock.unlock()
        }

        override func main() {
            _lock.lock()
            while true {
                while _blocks.count == 0 {
                    print("waiting...")
                    _lock.wait()
                }

                print("extracting block...")
                if let block = _blocks.first {
                    _blocks.removeFirst()
                    _lock.unlock()
                    print("running block...")
                    block;
                }

                _lock.lock()
            }
        }
    }
}

输出:

queueing openFile...
waiting...
extracting block...
running block...
waiting...

1 个答案:

答案 0 :(得分:0)

该块未运行,因为您只有block。您需要block(),例如:

if let block = _blocks.first as? ()->() {
    _blocks.removeFirst()
    _lock.unlock()
    print("running block...")
    block()
}