graphicsdriver/metal/mtl: Bug fix: Guard the handler map by a mutex

The handler is invoked in another thread than the main thread.
This commit is contained in:
Hajime Hoshi 2020-11-08 04:39:54 +09:00
parent 170ddd70a5
commit aaff18ecf7

View File

@ -27,6 +27,7 @@ package mtl
import ( import (
"errors" "errors"
"fmt" "fmt"
"sync"
"unsafe" "unsafe"
) )
@ -568,20 +569,30 @@ func (cb CommandBuffer) WaitUntilCompleted() {
C.CommandBuffer_WaitUntilCompleted(cb.commandBuffer) C.CommandBuffer_WaitUntilCompleted(cb.commandBuffer)
} }
var commandBufferCompletedHandlers = map[unsafe.Pointer]func(){} var (
commandBufferCompletedHandlers = map[unsafe.Pointer]func(){}
commandBufferCompletedHandlersM sync.Mutex
)
// AddCompletedHandler registers a block of code that Metal calls immediately after the GPU finishes executing the commands in the command buffer. // AddCompletedHandler registers a block of code that Metal calls immediately after the GPU finishes executing the commands in the command buffer.
// //
// Reference: https://developer.apple.com/documentation/metal/mtlcommandbuffer/1442997-addcompletedhandler // Reference: https://developer.apple.com/documentation/metal/mtlcommandbuffer/1442997-addcompletedhandler
func (cb CommandBuffer) AddCompletedHandler(f func()) { func (cb CommandBuffer) AddCompletedHandler(f func()) {
commandBufferCompletedHandlersM.Lock()
commandBufferCompletedHandlers[cb.commandBuffer] = f commandBufferCompletedHandlers[cb.commandBuffer] = f
commandBufferCompletedHandlersM.Unlock()
C.CommandBuffer_AddCompletedHandler(cb.commandBuffer) C.CommandBuffer_AddCompletedHandler(cb.commandBuffer)
} }
//export commandBufferCompletedCallback //export commandBufferCompletedCallback
func commandBufferCompletedCallback(commandBuffer unsafe.Pointer) { func commandBufferCompletedCallback(commandBuffer unsafe.Pointer) {
f := commandBufferCompletedHandlers[commandBuffer] f := commandBufferCompletedHandlers[commandBuffer]
commandBufferCompletedHandlersM.Lock()
delete(commandBufferCompletedHandlers, commandBuffer) delete(commandBufferCompletedHandlers, commandBuffer)
commandBufferCompletedHandlersM.Unlock()
f() f()
} }