For some reason, I wanted to install Swift on Ubuntu and try parallel processing, but it didn't work, so I'll show you the problem and the solution.
The environment I ran is as follows.
--I want to confirm that processing is executed in parallel for the time being. --Print numbers asynchronously
After investigating, it seems that it is common to use Dispatch queue
.
It seems that there are also Process
and Thread
, but Dispatchqueue
seems to make them easy to use, so I decided to use Dispatchqueue
obediently.
At first, copy the code of Site that came out after searching as it is, and do as follows Was there.
I ran swift package init --type executable
to generate various files and made main.swift as follows.
import Foundation
var value: Int = 2
DispatchQueue.main.async {
for i in 0...3 {
value = i
print("\(value) ✴️")
}
}
for i in 4...6 {
value = i
print("\(value) ✡️")
}
DispatchQueue.main.async {
value = 9
print(value)
}
However, the execution result is
4 ✡️
5 ✡️
6 ✡️
0 ✴️
1 ✴️
2 ✴️
3 ✴️
9
I wanted to be
4 ✡️
5 ✡️
6 ✡️
It has become.
In other words, the processing of the part left to ** Dispatchqueue
is not executed at all. ** **
I had one idea about this cause.
It was ** running the file alone **.
Many sites are intended for use within iPhone apps developed on the Mac.
In addition, I remembered that I had a similar problem before when running Swift as a single file. Below are the questions I posted at that time.
[Swift] Timer cannot be executed repeatedly (regular execution)
This is a problem because RunLoop, which is automatically executed in the application, is not executed when the Swift file is executed alone, and it is solved by adding RunLoop.current.run ()
to the end of the program. Did.
How did I add RunLoop.current.run ()
to this program as well?
import Foundation
var value: Int = 2
DispatchQueue.main.async {
for i in 0...3 {
value = i
print("\(value) ✴️")
}
}
for i in 4...6 {
value = i
print("\(value) ✡️")
}
DispatchQueue.main.async {
value = 9
print(value)
}
RunLoop.current.run()
Then, the output was as expected.
--When running Swift as a single file instead of an app, adding RunLoop may solve the problem. --When using Dispatch queue, add Run Loop
If you have any mistakes or improvements, please leave a comment or edit request. Thank you very much.
Recommended Posts