ios - 如何在swift中制作线程安全的代码块

标签 ios swift xcode multithreading locking

我尝试了 stackoverflow 上给出的多个解决方案/答案,但没有一个对我有用。其中一些如下:

https://stackoverflow.com/a/30495424/3145189

Is this safe to call wait() of DispatchSemaphore several times at one time?

https://stackoverflow.com/a/37155631/3145189

我正在尝试实现非常简单的事情,代码块或函数应该串行执行,而不管它是从哪个线程调用的。

我的示例代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

   DispatchQueue.global().async {
        self.testLog(name:"first")
    }
    DispatchQueue.global().async {
        self.testLog(name:"second")
    }

    DispatchQueue.main.async {
        self.testLog(name: "mainthread")
    }
}


func testLog(name:String) -> Void {
        for i in 1..<1000 {
            print("thread test \(i) name =\(name)")
        }

    }

所以输出应该是这样的-

第一次线程调用

线程测试 1 name =first

线程测试 2 name =first

线程测试 3 name =first

.

.

.

线程测试 999 name =first

第二个线程调用

线程测试 1 name =second

线程测试 2 name =second

.

.

.

线程测试 999 name =second

主线程调用

线程测试1名称=mainthread

线程测试2名称=mainthread

.

.

.

线程测试999 名称=mainthread

如果在第一个线程上调用函数,它应该只为第一个线程继续打印日志。线程的顺序可能会有所不同我不在乎意味着即使它首先打印主线程日志然后是第二个和第一个无关紧要日志应该被分组。

最佳答案

这将串行执行调用。 保留对 serialQueue 的引用,您可以从任何线程提交 block 。

let serialQueue = DispatchQueue(label: "serial_queue")

    serialQueue.async {
        self.testLog(name: "first")
    }
    serialQueue.async {
        self.testLog(name: "second")
    }

    serialQueue.async {
        self.testLog(name: "third")
    }

关于ios - 如何在swift中制作线程安全的代码块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51780904/

相关文章:

ios - tableView.reloadData()错误: Ambiguous reference to member

ios - 自动完成搜索栏

ios - 在定点上旋转 UIImageView

swift - 当抛出一个可选的-nil错误时,如何获得默认的错误字符串?

xcode - Swift UISplitViewController 具有用于详细 View 的多个 Storyboard

iphone - 如何以编程方式在 iOS 应用程序中显示目标的版本/内部版本号?

ios - 如何为 Alamofire 请求全局设置基本 url?

ios - 将 parse 中的数据保存为字符串

iOS - [CLPlacemark 时区] : unrecognized selector iOS 8

swift - Game Center 在 iOS 10 上没有显示任何数据