PerfectlySoft / Perfect

Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)
https://www.perfect.org
Apache License 2.0
13.83k stars 944 forks source link

Why theading not work #256

Closed fisherjoe closed 6 years ago

fisherjoe commented 6 years ago

When I use Theading as follow. My expected printed message is 『Do something first!』『After do something!』,but the result runing is opposite. Is there anything wrong about Threading ? And How could I perform in main thread?

func handler(request: HTTPRequest, response: HTTPResponse) {

let event = Threading.Event()
Threading.dispatch {
    Threading.sleep(seconds: 3)
    print("Do something first!")
    event.signal()
}

_ = event.wait()
print("After do something!")

// Respond with a simple message.
response.setHeader(.contentType, value: "text/html")
response.appendBody(string: "<html><title>Hello, world!</title><body>Hello, world!</body></html>")
// Ensure that response.completed() is called when your processing is done.
response.completed()

}

kjessup commented 6 years ago

You have to call .lock() before calling signal or wait, followed by .unlock(). It's described more in this document: https://www.perfect.org/docs/thread.html

fisherjoe commented 6 years ago

@kjessup Awesome, you are right. I have achieved it as follow: let event = Threading.Event(); event.lock(); Threading.dispatch { event.lock() Threading.sleep(seconds: 3) print("------->") event.signal() event.unlock() }

let wait = event.wait();
event.unlock();