Add garbage collection memory mangement mode (gogc). Lots of fixes

related to pointer handling and memory management.
This commit is contained in:
gmp
2019-06-18 09:15:46 -04:00
parent 79bb282188
commit e5c8e114bf
8 changed files with 342 additions and 109 deletions
+16 -6
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"git.wow.st/gmp/nswrap/examples/app/ns"
"runtime"
"time"
)
//Shortcut for literal NSStrings
@@ -31,8 +32,9 @@ func didFinishLaunching(n *ns.NSNotification) {
ns.NSBackingStoreBuffered,
0,
)
// retain win since we called Alloc and did not add it to a collection
win.Retain()
// We do not need to retain this because we are in garbage collection mode
// and have assigned it to a global variable.
//win.Retain()
win.SetTitle(nst("Hi World"))
win.MakeKeyAndOrderFront(win)
@@ -119,12 +121,12 @@ var (
)
func app() {
//Lock OS thread because Cocoa uses thread-local storage
// Lock OS thread because Cocoa uses thread-local storage
runtime.LockOSThread()
a = ns.NSApplicationSharedApplication()
a.SetActivationPolicy(ns.NSApplicationActivationPolicyRegular)
//Set up an AppDelegate
// Set up an AppDelegate
del := ns.AppDelegateAlloc()
del.ApplicationDidFinishLaunchingCallback(didFinishLaunching)
del.ApplicationShouldTerminateAfterLastWindowClosedCallback(shouldTerminateAfterLastWindowClosed)
@@ -133,12 +135,20 @@ func app() {
a.SetDelegate(del)
//Run the app
// Run the app
a.Run()
}
func main() {
//Run our app in an autorelease pool just for fun
// Run GC every second to ensure pointers are not being prematurely released.
go func() {
for {
runtime.GC()
time.Sleep(time.Second)
}
}()
// Run our app in an autorelease pool just for fun
go ns.Autoreleasepool(app)
select {}
}
+2 -1
View File
@@ -44,4 +44,5 @@ subclasses:
frameworks: [ Foundation, AppKit ]
pragma: [ clang diagnostic ignored "-Wformat-security" ]
autorelease: true
#autorelease: true
gogc: true
+44 -8
View File
@@ -5,6 +5,8 @@ import "C"
import (
"encoding/binary"
"fmt"
"runtime"
"time"
"git.wow.st/gmp/nswrap/examples/bluetooth/ns"
)
@@ -25,34 +27,53 @@ func updateState(c *ns.CBCentralManager) {
fmt.Printf(" powered on\n")
cm.ScanForPeripheralsWithServices(ns.NSArrayWithObjects(hrm_uuid), nil)
}
fmt.Printf("Go: updateState returning\n")
}
func discoverPeripheral(c *ns.CBCentralManager, p *ns.CBPeripheral, d *ns.NSDictionary, rssi *ns.NSNumber) {
fmt.Printf("Did discover peripheral\n")
c.StopScan()
if peripheral.Ptr() != nil {
// if we already have a pointer to a peripheral, check that this one is different,
// and if so release the old one. Be careful to check the Objective-C pointers
// here as the Go pointers will differ.
if peripheral != nil && p.Ptr() != peripheral.Ptr() {
peripheral.Release()
}
peripheral = p
// we need to take ownership of this peripheral so CoreBluetooth doesn't
// dealloc it.
peripheral.Retain()
c.ConnectPeripheral(peripheral, nil)
}
func connectPeripheral(c *ns.CBCentralManager, p *ns.CBPeripheral) {
fmt.Printf("Did connect peripheral\n")
// set ourselves up as a peripheral delegate
p.SetDelegate(cd)
// discover all services on this device
p.DiscoverServices(nil)
fmt.Printf("Go: discoverPeripheral returning\n")
}
func discoverServices(p *ns.CBPeripheral, e *ns.NSError) {
fmt.Printf("Did discover services\n")
p.Services().ObjectEnumerator().ForIn(func(o *ns.Id) bool {
serv := o.CBService()
uuid := serv.UUID()
switch {
case serv.UUID().IsEqualTo(hrm_uuid):
case uuid.IsEqualTo(hrm_uuid):
fmt.Printf("--heart rate monitor service\n")
p.DiscoverCharacteristics(nil, serv)
case serv.UUID().IsEqualTo(ns.CBUUIDWithGoString("180A")):
case uuid.IsEqualTo(info_uuid):
fmt.Printf("--device information service\n")
p.DiscoverCharacteristics(nil, serv)
default:
@@ -60,6 +81,7 @@ func discoverServices(p *ns.CBPeripheral, e *ns.NSError) {
}
return true
})
fmt.Printf("Go: discoverServices returning\n")
}
func hr(d *ns.NSData) int {
@@ -77,12 +99,14 @@ func hr(d *ns.NSData) int {
func discoverCharacteristics(p *ns.CBPeripheral, s *ns.CBService, e *ns.NSError) {
fmt.Printf("Did discover characteristics\n")
fmt.Printf("----%s\n", s.UUID().UUIDString().UTF8String())
if s.UUID().IsEqualTo(hrm_uuid) {
uuid := s.UUID()
fmt.Printf("----%s\n", uuid.UUIDString().UTF8String())
if uuid.IsEqualTo(hrm_uuid) {
s.Characteristics().ObjectEnumerator().ForIn(func(o *ns.Id) bool {
chr := o.CBCharacteristic()
fmt.Printf("------%s\n", chr.UUID().UUIDString().UTF8String())
if chr.UUID().IsEqualTo(hrv_uuid) {
chuuid := chr.UUID()
fmt.Printf("------%s\n", chuuid.UUIDString().UTF8String())
if chuuid.IsEqualTo(hrv_uuid) {
p.SetNotifyValue(1, chr)
v := chr.Value()
fmt.Println(hr(v))
@@ -90,6 +114,7 @@ func discoverCharacteristics(p *ns.CBPeripheral, s *ns.CBService, e *ns.NSError)
return true
})
}
fmt.Printf("Go: discoverCharacteristics returning\n")
}
func updateValue(p *ns.CBPeripheral, chr *ns.CBCharacteristic, e *ns.NSError) {
@@ -97,11 +122,13 @@ func updateValue(p *ns.CBPeripheral, chr *ns.CBCharacteristic, e *ns.NSError) {
v := chr.Value()
fmt.Printf("Heart rate: %d\n", hr(v))
}
fmt.Printf("Go: updateValue returning\n")
}
var (
hrm_uuid *ns.CBUUID
hrv_uuid *ns.CBUUID
info_uuid *ns.CBUUID
cd *ns.CBDelegate
cm *ns.CBCentralManager
peripheral *ns.CBPeripheral
@@ -121,9 +148,18 @@ func main() {
hrm_uuid = ns.CBUUIDWithGoString("180D")
hrv_uuid = ns.CBUUIDWithGoString("2A37")
info_uuid = ns.CBUUIDWithGoString("180A")
//We defined our own queue because this won't work on the main queue.
// We defined our own queue because this won't work on the main queue.
cm = ns.CBCentralManagerAlloc().InitWithDelegateQueue(cd, queue)
// For debugging purposes, run GC every second to make sure things are not
// over-released.
go func() {
for {
runtime.GC()
time.Sleep(time.Second)
}
}()
select {}
}
+2 -1
View File
@@ -22,6 +22,7 @@ classes:
- NSDictionary
- NSEnumerator
- NSString
- NSAutoreleasePool
functions: [ NSMakeRange, dispatch_queue_create ]
enums: [ CB.* ]
@@ -38,4 +39,4 @@ delegates:
- peripheralDidUpdateValueForCharacteristic
pragma: [ clang diagnostic ignored "-Wformat-security" ]
#gogc: true
gogc: true
+64 -19
View File
@@ -15,6 +15,7 @@ func releaseX(x int) func (ns.MyClassSupermethods) {
super.Release() // comment out for leak
}
}
func memtest1() {
fmt.Println("memtest1 started")
for {
@@ -33,7 +34,7 @@ func memtest1() {
// in a real program.
runtime.GC()
time.Sleep(time.Second/50)
fmt.Printf("Loop complete\n")
//fmt.Printf("Loop complete\n")
}
}
@@ -52,18 +53,35 @@ func memtest2() {
o4 := ns.NSStringAlloc()
_ = o4
//arr := ns.NSArrayAlloc().InitWithObjects(o1,o1)
arr := ns.NSArrayWithObjects(o1,o2,o3,o4)
_ = arr
a1 := ns.NSArrayAlloc()
// init methods in Objective-C always return a retained object.
// init may or may not return the same object that was sent in.
a1 = a1.InitWithObjects(o1,o2,o3,o4)
a2 := ns.NSArrayWithObjects(o1,o2,o3,o4)
// you can always nest alloc and init.
a3 := ns.NSMutableArrayAlloc().Init()
a3.AddObject(o1)
a3.AddObject(o2)
a3.AddObject(o3)
a3.AddObject(o4)
_ = a1
_ = a2
_ = a3
//o1.Release()
//o1.Release()
runtime.GC()
time.Sleep(time.Second/50)
}
}
func addStr(arr *ns.NSMutableArray) {
// temporary strings made by the 'WithGoString' methods should be released
// automatically by the GC.
s1 := ns.NSStringAlloc().InitWithGoString("a string")
arr.AddObject(s1)
@@ -75,24 +93,35 @@ func addStr(arr *ns.NSMutableArray) {
func memtest3() {
fmt.Println("memtest3 started")
arr := ns.NSMutableArrayAlloc().Init() // arr will be garbage collected by Go
addStr(arr)
runtime.GC()
time.Sleep(time.Second)
s1 := arr.ObjectAtIndex(0)
fmt.Println(s1.NSString().UTF8String())
fmt.Println("memtest3 done")
for {
// arr will be garbage collected by Go
arr := ns.NSMutableArrayAlloc().Init()
addStr(arr)
runtime.GC()
time.Sleep(time.Second)
// check that our string was retained.
s1 := arr.ObjectAtIndex(0)
gstr := s1.NSString().UTF8String().String()
_ = gstr
}
}
func memtest4() {
fmt.Println("memtest4 started")
for {
o1 := ns.NSStringAlloc().InitWithGoString("four string")
o1 := ns.NSStringAlloc().InitWithGoString("red string")
// conversions to UTF8String internally create autoreleased strings
// in the Objective-C runtime. NSWrap runs these in a mini-
// @autoreleasepool block.
c1 := o1.UTF8String()
_ = o1
_ = c1
runtime.GC()
time.Sleep(time.Second/10)
time.Sleep(time.Second/50)
}
}
@@ -100,12 +129,21 @@ func memtest5() {
fmt.Println("memtest5 started")
i := 0
for {
str := ns.NSStringWithGoString(fmt.Sprintf("five string %d",i))
_ = str
// by incrementing i we can ensure that Objective-C needs to create
// a new NSString object at each loop iteration and cannot be reusing
// the same string object.
str := ns.NSStringWithGoString(fmt.Sprintf("blue string %d",i))
// SubstringFromIndex should be returning a newly allocated NSString,
// which is getting retained by NSWrap and released by a Go GC
// finalizer.
sub := str.SubstringFromIndex(5)
_ = sub
fmt.Printf("sub = %s\n",sub)
time.Sleep(time.Second/10)
u := sub.UTF8String()
_ = u
time.Sleep(time.Second/50)
runtime.GC()
i++
}
@@ -117,5 +155,12 @@ func main() {
go memtest3()
go memtest4()
go memtest5()
go func() {
for {
// print a progress indicator
fmt.Printf("t = %s\n",time.Now())
time.Sleep(time.Second * 10)
}
}()
select {}
}