Skip to content

Instantly share code, notes, and snippets.

@RockfordWei
Created August 22, 2017 14:55
Show Gist options
  • Save RockfordWei/6f7ab9d66e975ce83b09db5b21c2d726 to your computer and use it in GitHub Desktop.
Save RockfordWei/6f7ab9d66e975ce83b09db5b21c2d726 to your computer and use it in GitHub Desktop.
How to reuse Perfect Swift MySQL connection threaded safely.
import MySQL
import PerfectThread
#if os(Linux)
import Glibc
#else
import Darwin
#endif
let mysql = MySQL()
let lock = Threading.Lock()
var jobs = 10
func now(_ id: Int) {
print("Job Now #", id)
lock.doWithLock {
let x = mysql.query(statement: "SELECT now() as time")
guard x, let y = mysql.storeResults(),
let row = y.next() else {
print(mysql.errorMessage())
return
}
print(row[0] ?? "Now() FAILED")
y.close()
jobs -= 1
}
}
func user(_ id: Int) {
print("Job Usr #", id)
lock.doWithLock {
let x = mysql.query(statement: "select User from user")
guard x, let y = mysql.storeResults(),
let row = y.next() else {
print(mysql.errorMessage())
return
}
print(row[0] ?? "User() FAILED")
y.close()
jobs -= 1
}
}
_ = mysql.setOption(.MYSQL_SET_CHARSET_NAME, "utf8mb4")
guard mysql.connect(host: "127.0.0.1", user: "root", password: "your pass", db: "mysql") else {
print(mysql.errorMessage())
exit(0)
}
jobs = 10
for id in 0 ..< 5 {
Threading.dispatch {
now(id)
}
Threading.dispatch {
user(id)
}
}
while jobs > 0 {
sleep(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment