Remove node from ARSCNView cause random crash(btCollisionWorld::updateSingleAabb) - scenekit

I made a ball drop animation on the ARSCNView, then after 1 second, then deleted the ball and re-added it to the original position on the view, but this occasionally crashes.
something like this:
private func dropBall(){
// do ball dropping animation
let randomX = Float.random(in: -2...2) * 0.001
let randomY = Float.random(in: 3...10) * 0.001
ballNode?.physicsBody = SCNPhysicsBody(type: .dynamic, shape: nil)
ballNode?.physicsBody?.mass = 0.005
let position = SCNVector3(x: 0.05, y: 0.05, z: 0.05)
let force = SCNVector3(x: randomX, y: randomY , z: 0)
ballNode?.physicsBody?.applyForce(force, at: position, asImpulse: true)
let tv = SCNVector4(x: -0.2 + Float(0.4 * randomCGFloat()), y: 0 , z: 0.2, w: 0)
ballNode?.physicsBody?.applyTorque(tv, asImpulse: true)
//remove the ball
DispatchQueue.main.asyncAfter(deadline: .now() + 1){
self.ballNode?.physicsBody = nil
self.ballNode?.removeFromParentNode()
self.ballNode = nil
// add ball again
let ballNode = SCNReferenceNode(named: "myscn.scn")
contentNode?.addChildNode(ballNode)
self.ballNode = ballNode
}
}
crash stack:
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000068
Exception Codes: 0x0000000000000001, 0x0000000000000068
VM Region Info: 0x68 is not in any region. Bytes before following region: 68719476632
REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL
UNUSED SPACE AT START
--->
commpage (reserved) 1000000000-7000000000 [384.0G] ---/--- SM=NUL ...(unallocated)
Termination Reason: SIGNAL 11 Segmentation fault: 11
Terminating Process: exc handler [30984]
Triggered by Thread: 11
Thread 11 name:
Thread 11 Crashed:
0 SceneKit 0x00000001cf3ef998 btDbvtBroadphase::setAabb(btBroadphaseProxy*, btVector3 const&, btVector3 const&, btDispatcher*) + 52
1 SceneKit 0x00000001cf65126c btCollisionWorld::updateSingleAabb(btCollisionObject*) + 284
2 SceneKit 0x00000001cf65133c btCollisionWorld::updateAabbs() + 56
3 SceneKit 0x00000001cf3ff39c btCollisionWorld::performDiscreteCollisionDetection() + 32
4 SceneKit 0x00000001cf406964 btDiscreteDynamicsWorld::internalSingleStepSimulation(float) + 120
5 SceneKit 0x00000001cf3ff574 btDiscreteDynamicsWorld::stepSimulation(float, int, float) + 276
6 SceneKit 0x00000001cf507ad8 -[SCNPhysicsWorld _step:] + 156 (SCNPhysicsWorld.mm:1423)
7 SceneKit 0x00000001cf3ae9fc -[SCNRenderer _update:] + 932 (SCNRenderer.m:3814)
8 SceneKit 0x00000001cf3ae364 -[SCNRenderer _drawSceneWithNewRenderer:] + 152 (SCNRenderer.m:5303)
9 SceneKit 0x00000001cf3ae278 -[SCNRenderer _drawScene:] + 40 (SCNRenderer.m:5537)
10 SceneKit 0x00000001cf3a78b4 -[SCNRenderer _drawAtTime:] + 500 (SCNRenderer.m:5727)
11 SceneKit 0x00000001cf3a74cc -[SCNView _drawAtTime:] + 368 (SCNView.m:1542)
12 SceneKit 0x00000001cf4ba478 __83-[NSObject(SCN_DisplayLinkExtensions) SCN_setupDisplayLinkWithQueue:screen:policy:]_block_invoke + 44 (SCNDisplayLink_ARC.m:42)
13 SceneKit 0x00000001cf595fa0 -[SCNDisplayLink _displayLinkCallbackReturningImmediately] + 148 (SCNDisplayLink.m:381)
How to fix this?
This will only crash by chance and is not too easy to reproduce, is there a problem with me deleting this node in this way?

Related

SwiftUI Crash in ForEach Loop

ScrollView(.horizontal, showsIndicators: false, content: {
LazyHGrid(rows: gridLayout2, alignment: .center, spacing: columnSpacing, pinnedViews: [], content: {
Section(
header: SectionView(rotateClockwise: false, headerText: "Premium Store"),
footer: SectionView(rotateClockwise: true, headerText: "Premium Store")) {
ForEach(premiumStoreItems) { item in
StoreItemView(storeItem: item)
}
}
}) //: LAZYHGRID
.frame(height: 200)
.padding(15)
})
The crash is occurring in the ForEach loop.
If I comment the ForEach and pass in 1 specific item from my array, it works fine. However I need to display all my items in my array.
I am not sure what to do here.
The following code works fine.
//ForEach(premiumStoreItems) { item in
StoreItemView(storeItem: premiumStoreItems[0])
//}
CRASH LOG (sorry I didnt know where to get it)
Application Specific Information:
Fatal error: each layout item may only occur once: file SwiftUI, line 0
------ FULL CRASH LOG
Process: AppExample001 [3525]
Path: /Users/USER/Library/Developer/Xcode/UserData/Previews/Simulator Devices/C93C2BE8-C23A-4813-9D6C-110E87786FFE/data/Containers/Bundle/Application/40562FF7-7B66-4BE4-915A-5A2A35AD3EC2/AppExample001.app/AppExample001
Identifier: AppExample001
Version: 1.0 (1)
Code Type: X86-64 (Native)
Parent Process: launchd_sim [2488]
Responsible: SimulatorTrampoline [611]
User ID: 501
Date/Time: 2021-04-07 12:23:50.173 -0400
OS Version: macOS 11.2.3 (20D91)
Report Version: 12
Bridge OS Version: 5.2 (18P4347)
Anonymous UUID: 5A68DF80-DD1B-1132-4597-BBC26C334627
Time Awake Since Boot: 7000 seconds
System Integrity Protection: enabled
Crashed Thread: 0 Dispatch queue: com.apple.main-thread
Exception Type: EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes: 0x0000000000000001, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Termination Signal: Illegal instruction: 4
Termination Reason: Namespace SIGNAL, Code 0x4
Terminating Process: exc handler [3525]
ID Vend/Dev
95f5 687f1002
Seconds Ago ID Type
6900.0 95f5 Attach
Application Specific Information:
Fatal error: each layout item may only occur once: file SwiftUI, line 0
CoreSimulator 732.18.6 - Device: iPhone SE (2nd generation) (C93C2BE8-C23A-4813-9D6C-110E87786FFE) - Runtime: iOS 14.4 (18D46) - DeviceType: iPhone SE (2nd generation)
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 libswiftCore.dylib 0x00007fff2fc85004 assertionFailure(::file:line:flags:) + 532
1 com.apple.SwiftUI 0x00007fff572e9d24 ViewCache.commitPlacedChildren(from:to:) + 4020
2 com.apple.SwiftUI 0x00007fff571a1f16 specialized IncrementalChildPlacements.updateValue() + 1558
3 com.apple.SwiftUI 0x00007fff572be37f partial apply for specialized implicit closure #2 in implicit closure #1 in closure #1 in closure #1 in Attribute.init(:) + 15
4 com.apple.AttributeGraph 0x00007fff4cd78723 AG::Graph::UpdateStack::update() + 505
5 com.apple.AttributeGraph 0x00007fff4cd78bb9 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, bool) + 335
6 com.apple.AttributeGraph 0x00007fff4cd7d85f AG::Graph::input_value_ref_slow(AG::data::ptr<AG::Node>, AG::AttributeID, unsigned int, AGSwiftMetadata const*, bool*, long) + 523
7 com.apple.AttributeGraph 0x00007fff4cd8edc5 AGGraphGetValue + 203
8 com.apple.SwiftUI 0x00007fff572edac0 IncrementalPreference.children.getter + 48
9 com.apple.SwiftUI 0x00007fff572edb95 IncrementalPreference.value.getter + 85
10 com.apple.SwiftUI 0x00007fff572ede1c protocol witness for Rule.value.getter in conformance IncrementalPreference + 28
11 com.apple.AttributeGraph 0x00007fff4cd91907 dispatch thunk of Rule.value.getter + 7
12 com.apple.SwiftUI 0x00007fff570e9a18 implicit closure #2 in implicit closure #1 in closure #1 in closure #1 in Attribute.init(_:) + 56
13 com.apple.AttributeGraph 0x00007fff4cd78723 AG::Graph::UpdateStack::update() + 505
14 com.apple.AttributeGraph 0x00007fff4cd78bb9 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, bool) + 335
15 com.apple.AttributeGraph 0x00007fff4cd7d318 AG::Graph::value_ref(AG::AttributeID, AGSwiftMetadata const*, bool*) + 130
16 com.apple.AttributeGraph 0x00007fff4cd8ee13 AGGraphGetValue + 281
17 com.apple.SwiftUI 0x00007fff57987807 GraphHost.updatePreferences() + 39
18 com.apple.SwiftUI 0x00007fff57458cbf ViewGraph.updateOutputs(at:) + 95
19 com.apple.SwiftUI 0x00007fff573f04e4 specialized closure #1 in ViewRendererHost.render(interval:updateDisplayList:) + 1316
20 com.apple.SwiftUI 0x00007fff573ed28e specialized ViewRendererHost.render(interval:updateDisplayList:) + 366
21 com.apple.SwiftUI 0x00007fff57a59c0e specialized UIHostingController._render(seconds:) + 46
22 com.apple.dt.XCPreviewKit 0x000000010c117536 0x10c10a000 + 54582
23 com.apple.dt.XCPreviewKit 0x000000010c1246eb 0x10c10a000 + 108267
24 com.apple.dt.XCPreviewKit 0x000000010c11b91f 0x10c10a000 + 71967
25 com.apple.dt.XCPreviewKit 0x000000010c11bc08 0x10c10a000 + 72712
26 com.apple.dt.XCPreviewKit 0x000000010c11ddff 0x10c10a000 + 81407
27 com.apple.dt.XCPreviewKit 0x000000010c11c274 0x10c10a000 + 74356
28 com.apple.dt.XCPreviewKit 0x000000010c1134e3 0x10c10a000 + 38115
29 com.apple.dt.XCPreviewKit 0x000000010c112eee 0x10c10a000 + 36590
30 libdispatch.dylib 0x00007fff2010532f _dispatch_call_block_and_release + 12
31 libdispatch.dylib 0x00007fff20106508 _dispatch_client_callout + 8
32 libdispatch.dylib 0x00007fff20112ff7 dispatch_main_queue_callback_4CF + 1045
33 com.apple.CoreFoundation 0x00007fff2038fdbb CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 9
34 com.apple.CoreFoundation 0x00007fff2038a63e __CFRunLoopRun + 2685
35 com.apple.CoreFoundation 0x00007fff203896d6 CFRunLoopRunSpecific + 567
36 com.apple.GraphicsServices 0x00007fff2c257db3 GSEventRunModal + 139
37 com.apple.UIKitCore 0x00007fff24696cf7 -[UIApplication run] + 912
38 com.apple.UIKitCore 0x00007fff2469bba8 UIApplicationMain + 101
39 com.apple.SwiftUI 0x00007fff5791abc7 closure #1 in KitRendererCommon(:) + 119
40 com.apple.SwiftUI 0x00007fff5791ab3f runApp(:) + 143
41 com.apple.SwiftUI 0x00007fff5745212d static App.main() + 61
42 com.oneorangetree.AppExample001 0x000000010bfcaf4e static AppExample001App.$main() + 78
43 com.oneorangetree.AppExample001 0x000000010bfcafd4 main + 20
44 libdyld.dylib 0x00007fff2025a3e9 start + 1
ForEach is unable to identify the each item uniquely,
make sure your data model struct is confirm to identifiable protocol
try this on
ForEach(premiumStoreItems, id:\.self)
ForEach(premiumStoreItems, id:\.id) // if you've unique identifier with the name of "id"

Swift 3 - Core Data - create object

So I am trying to fetch my data from my core data database, put it into objects and then into an array which I then callback.
func getCoffeeBrandsFromDB(callback: #escaping (_ dbCoffeeBrands: Array<Any>)-> ()) {
//create a fetch request, telling it about the entity
print("running getCBFDB")
var coffeeBrandArray = Array<Any>()
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "CoffeeBrand")
do {
let searchResults = try getContext().fetch(fetchRequest)
print ("num of results = \(searchResults.count)")
for brands in searchResults as! [NSManagedObject] {
let brand = CoffeeBrand()
brand.dataBaseId = brands.value(forKey: "dataBaseId") as! Int64
brand.brandName = brands.value(forKey: "brandName") as? String
brand.numberOfCoffeesNeeded = brands.value(forKey: "numberOfCoffeesNeeded") as! Int32
coffeeBrandArray.append(brand)
print("brands virker med \(brand.brandName!)")
}
print("CcffeeBrandArray.count is: \(coffeeBrandArray.count)")
callback(coffeeBrandArray)
} catch {
print("Error with request: \(error)")
}
}
When I run getCoffeeBrandsFromDB I get this errorlog:
running getCBFDB
num of results = 4
2017-02-08 15:47:02.179211 Keebin_development_1[8373:626945] [error] error: CoreData: error: Failed to call designated initializer on NSManagedObject class 'CoffeeBrand'
CoreData: error: CoreData: error: Failed to call designated initializer on NSManagedObject class 'CoffeeBrand'
2017-02-08 15:47:02.180 Keebin_development_1[8373:626945] -[CoffeeBrand setDataBaseId:]: unrecognized selector sent to instance 0x608000279e80
2017-02-08 15:47:02.189 Keebin_development_1[8373:626945] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CoffeeBrand setDataBaseId:]: unrecognized selector sent to instance 0x608000279e80'
*** First throw call stack:
(
0 CoreFoundation 0x0000000110c36d4b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x000000011027721e objc_exception_throw + 48
2 CoreFoundation 0x0000000110ca6f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x0000000110bbc005 ___forwarding___ + 1013
4 CoreFoundation 0x0000000110bbbb88 _CF_forwarding_prep_0 + 120
5 Keebin_development_1 0x000000010fc20e5c _TF20Keebin_development_121getCoffeeBrandsFromDBFT8callbackFGSaP__T__T_ + 1804
6 Keebin_development_1 0x000000010fc2d314 _TFC20Keebin_development_126LoyaltyCardsViewController11viewDidLoadfT_T_ + 180
7 Keebin_development_1 0x000000010fc2d5e2 _TToFC20Keebin_development_126LoyaltyCardsViewController11viewDidLoadfT_T_ + 34
8 UIKit 0x00000001111fca3d -[UIViewController loadViewIfRequired] + 1258
9 UIKit 0x000000011123d28f -[UINavigationController _layoutViewController:] + 55
10 UIKit 0x000000011123db77 -[UINavigationController _updateScrollViewFromViewController:toViewController:] + 471
11 UIKit 0x000000011123dcee -[UINavigationController _startTransition:fromViewController:toViewController:] + 133
12 UIKit 0x000000011123eef9 -[UINavigationController _startDeferredTransitionIfNeeded:] + 874
13 UIKit 0x000000011123ffdb -[UINavigationController __viewWillLayoutSubviews] + 58
14 UIKit 0x0000000111436dd7 -[UILayoutContainerView layoutSubviews] + 223
15 UIKit 0x000000011111fab8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237
16 QuartzCore 0x00000001161ffbf8 -[CALayer layoutSublayers] + 146
17 QuartzCore 0x00000001161f3440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
18 QuartzCore 0x00000001161f32be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
19 QuartzCore 0x0000000116181318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280
20 QuartzCore 0x00000001161ae3ff _ZN2CA11Transaction6commitEv + 475
21 UIKit 0x0000000111053d9b _UIApplicationFlushRunLoopCATransactionIfTooLate + 206
22 UIKit 0x000000011185e77c __handleEventQueue + 5672
23 CoreFoundation 0x0000000110bdb761 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
24 CoreFoundation 0x0000000110bc098c __CFRunLoopDoSources0 + 556
25 CoreFoundation 0x0000000110bbfe76 __CFRunLoopRun + 918
26 CoreFoundation 0x0000000110bbf884 CFRunLoopRunSpecific + 420
27 GraphicsServices 0x00000001152f9a6f GSEventRunModal + 161
28 UIKit 0x000000011105ac68 UIApplicationMain + 159
29 Keebin_development_1 0x000000010fc3fe5f main + 111
30 libdyld.dylib 0x000000011434d68d start + 1
31 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
I can't seem to figure out where my problem is. I have created my CoffeeBrand+CoreDataClass.Swift and CoffeeBrand+CoreDataProperties.Swift with the editor-> create NSManaged Object Subclass and as other SO questions/answered has said with the codegen to manual/none.
The two classes mentioned:
import Foundation
import CoreData
#objc(CoffeeBrand)
public class CoffeeBrand: NSManagedObject {
}
and:
import Foundation
import CoreData
extension CoffeeBrand {
#nonobjc public class func fetchRequest() -> NSFetchRequest<CoffeeBrand> {
return NSFetchRequest<CoffeeBrand>(entityName: "CoffeeBrand");
}
#NSManaged public var brandName: String?
#NSManaged public var dataBaseId: Int64
#NSManaged public var id: Int64
#NSManaged public var numberOfCoffeesNeeded: Int32
}
Can someone see where I'm going wrong? Obviously it's in my for-loop but I don't know where/what/how to do it right.
Thanks in advance!
I figured out where I went wrong.
I changed let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "CoffeeBrand")
to
let fetchRequest: NSFetchRequest<NSManagedObject> = NSFetchRequest(entityName: "CoffeeBrand")
this way it is objects I fetch from the DB.
Then it was easy. Now my for-loop is simply:
for brands in searchResults {
coffeeBrandArray.append(brands)
}
callback(coffeeBrandArray)
} catch {
print("Error with request: \(error)")
}
}
And now everything works as it should.

Converting an array containing structure to json

I'm trying to convert an array into json but can't get it to work. It says the array is an invalid type to convert to json, but it's just an array of ints.
//These are for me to able to use time
let date = NSDate()
let calendar = NSCalendar.current
//This is the structure that my array will be filled with
struct Day
{
var week: Int?
var date: Int?
var month: Int?
var year: Int?
var weekday: Int?
}
//This is my array
var theArrayContainingAllTheUserData = [Day]()
var numberofloops = 0
//This is a loop that fills my array with data
while theArrayContainingAllTheUserData.count < 20
{
var theincreasingnumberofdays: NSDate {
return NSCalendar.current.date(byAdding: .day, value: numberofloops, to: NSDate() as Date)! as NSDate
}
let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
numberofloops=numberofloops+1
var ScoopDay = Day()
ScoopDay.week=Int(myCalendar.component(.weekOfYear, from: theincreasingnumberofdays as Date!))
ScoopDay.date=Int(myCalendar.component(.day, from: theincreasingnumberofdays as Date!))
ScoopDay.month=Int(myCalendar.component(.month, from: theincreasingnumberofdays as Date!))
ScoopDay.year=Int(myCalendar.component(.year, from: theincreasingnumberofdays as Date!))
ScoopDay.weekday=Int(myCalendar.component(.weekday, from: theincreasingnumberofdays as Date!))
theArrayContainingAllTheUserData.append(ScoopDay)
}
//And here is my failed attempt at converting it to json
do {
let jsonData = try JSONSerialization.data(withJSONObject: theArrayContainingAllTheUserData, options: JSONSerialization.WritingOptions.prettyPrinted)
} catch {
print(error.localizedDescription)
}
Getting Error:
2016-10-28 13:20:09.669 jsona arrayen[3284:332873] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'
First throw call stack:
(
0 CoreFoundation 0x000000010840834b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x0000000107e6921e objc_exception_throw + 48
2 CoreFoundation 0x0000000108471265 +[NSException raise:format:] + 197
3 Foundation 0x000000010795d284 _writeJSONValue + 668
4 Foundation 0x000000010795d6d9 ___writeJSONArray_block_invoke + 132
5 CoreFoundation 0x00000001083ae36f __NSArrayEnumerate + 607
6 Foundation 0x000000010795d3df _writeJSONArray + 330
7 Foundation 0x000000010795d204 _writeJSONValue + 540
8 Foundation 0x000000010795cf94 -[_NSJSONWriter dataWithRootObject:options:error:] + 124
9 Foundation 0x000000010795ce74 +[NSJSONSerialization dataWithJSONObject:options:error:] + 333
10 ??? 0x0000000116ddd3cb 0x0 + 4678603723
11 jsona arrayen 0x0000000107892620 main + 0
12 CoreFoundation 0x00000001083ad25c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
13 CoreFoundation 0x0000000108392304 __CFRunLoopDoBlocks + 356
14 CoreFoundation 0x0000000108391a75 __CFRunLoopRun + 901
15 CoreFoundation 0x0000000108391494 CFRunLoopRunSpecific + 420
16 GraphicsServices 0x000000010d796a6f GSEventRunModal + 161
17 UIKit 0x0000000108f3bf34 UIApplicationMain + 159
18 jsona arrayen 0x00000001078926e9 main + 201
19 libdyld.dylib 0x000000010b8e968d start + 1
20 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Processing arrays in Go parallel gives unexpected results

I am interested to calculate correlations in parallel in Go. The main problem I have is that all the Go processes seems to execute exactly the same calculation. I reproduced here the problem with a very simple example.
I obtain :
4 + 50 = 54
4 + 50 = 54
4 + 50 = 54
instead of :
1 + 20 = 21
2 + 30 = 32
3 + 40 = 43
If I move up "wg.Wait()" I obtain the good result but no parallelism :(
Thank's in advance for your comments !
package main
import (
"fmt"
"runtime"
"sync"
)
func process_array(x, y int) int {
r := x + y
return r
}
func main() {
a1 := []int{0, 1, 2, 3, 4}
a2 := []int{10, 20, 30, 40, 50}
runtime.GOMAXPROCS(8)
var wg sync.WaitGroup
for i := 1; i < 4 ; i++ {
wg.Add(1)
go func() {
defer wg.Done()
x :=process_array(a1[i],a2[i])
fmt.Println(a1[i],"+", a2[i],"=", x)
}()
//wg.Wait() give the good result
//but it is not parallel processing
// 1 + 20 = 21
// 2 + 30 = 32
// 3 + 40 = 43
}
wg.Wait() // give a repetition of the same result :
// 4 + 50 = 54
// 4 + 50 = 54
// 4 + 50 = 54
}
You're accessing the same copy of i in all goroutines. The output you see is because the loop happens to finish before any of the goroutines start executing.
This means that i has the same value in all goroutines, i.e. the last value it had in the loop.
Passing i as an argument to each of your goroutines, thereby operating on a copy per goroutine instead, solves this problem.
The reason you saw the result you expected when you added wg.Wait() in the loop is because you then introduced synchronization, waiting for the goroutine to finish before starting the next one. That means the execution was in fact serial, not parallell.
Here's the updated code, which works as you'd expect:
package main
import (
"fmt"
"runtime"
"sync"
)
func process_array(x, y int) int {
r := x + y
return r
}
func main() {
a1 := []int{0, 1, 2, 3, 4}
a2 := []int{10, 20, 30, 40, 50}
runtime.GOMAXPROCS(8)
var wg sync.WaitGroup
for i := 1; i < 4; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
x := process_array(a1[i], a2[i])
fmt.Println(a1[i], "+", a2[i], "=", x)
}(i)
//wg.Wait() give the good result
//but it is not parallel processing
// 1 + 20 = 21
// 2 + 30 = 32
// 3 + 40 = 43
}
wg.Wait() // give a repetition of the same result :
// 4 + 50 = 54
// 4 + 50 = 54
// 4 + 50 = 54
}

What does "linear interpolation" mean?

I often hear the term "linear interpolation" in context with animations in WPF. What exactly does "linear interpolation" mean? Could you give me an example where to use "linear interpolation"?
Linear means lines (straight ones).
Interpolation is the act of finding a point within two other points. Contrast this with extrapolation, which is finding a point beyond the ends of a line.
So linear interpolation is the use of a straight line to find a point between two others.
For example:
*(5,10)
/
/
/
/
*(0,0)
You can use the two endpoints with linear interpolation to get the points along the line:
(1,2)
(2,4)
(3,6)
(4,8)
and linear extrapolation to get (for example):
(1000,2000)
(-1e27,-2e27)
In animation, let's say you have a bouncing ball that travels from the (x,y) position of (60,22) to (198,12) in 10 seconds.
With an animation rate of 10 frames per second, you can calculate it's position at any time with:
x0 = 60, y0 = 22
x1 = 198, y1 = 12
frames = 100
for t = 0 to frames:
x = (x1 - x0) * (t / frames) + x0
y = (y1 - y0) * (t / frames) + y0
Those two formulae at the bottom are examples of linear interpolation. At 50% (where t == 50):
x = (198 - 60) * (50 / 100) + 60
= 138 * 0.5 + 60
= 69 + 60
= 129
y = (12 - 22) * (50 / 100) + 22
= -10 * 0.5 + 22
= -5 + 22
= 17
and (129,17) is the midpoint between the starting and ending positions.
E.g. when you want a storyboard to move an element from one position to another using a fixed speed, then you'd use linear interpolation between the start and end positions.

Resources