我正在尝试将处理模式从Java应用程序移植到Swift应用程序,但是我在Swift中找不到匹配的结构来允许我这样做。该模式是用一个工作线程设计的,该工作线程会在需要处理模型时进行处理。请求不包含任何数据,工作线程在编译时定义了工作,并且未返回工作。问题是,如果要求工作线程在处理过程中进行其他工作,则需要这些请求成为幂等。
有人知道在Swift中复制它的方法吗?我看不到构造简单线程或创建线程安全变量的任何方法。我在NSOperation或Dispatch上看到的所有解决方案似乎都没有捆绑请求的方法。他们想为每个请求启动一个线程。
(要获得奖励积分,此模式是否有名称?我找不到一个名称,但是如果我知道,它可能会使我的Google搜索更容易。)
示例执行流程:
Thread A requests work
Worker Thread(WT) starts working
Thread B requests work
WT finishes work
WT Starts working
WT Finishes work
Thread A requests work
Worker Thread(WT) starts working
Thread B requests work
Thread A requests work
WT finishes work
WT Starts working
WT Finishes work
对于更多面向代码的人来说,用Java编写的概念证明片段:
import java.util.concurrent.atomic.AtomicBoolean;
class Main {
AtomicBoolean lock = new AtomicBoolean(false);
//Worker thread
private final Thread worker = new Thread(){
int timesRun = 0;
public void run(){
while(true){
//Make sure there has been a request since last time we started
while(!lock.getAndSet(false)){
yield();
}
System.out.println(timesRun++);
//Simulate lots of work
try{Thread.sleep(750);}catch(Exception e){}
}
}
};
public void run() throws Exception{
worker.start();
//Proof of concept
//These set calls come from many different threads
lock.set(true);//Causes execution
Thread.sleep(1000);
lock.set(true);//Causes execution
lock.set(true);//Does NOT cause execution
Thread.sleep(1000);
lock.set(true);//Causes execution
Thread.sleep(1000);
}
public static void main(String[] args) throws Exception{
new Main().run();
}
}