register.go 1019 字节
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
package main

/*
typedef int reader;
typedef int writer;
*/
import "C"

import "sync"

var mu sync.Mutex
var handleMap = make(map[C.reader]*reader)
var curHandle C.reader
var writerMap = make(map[C.writer]*writer)
var curWriterHandle C.writer

func addReader(r *reader) C.reader {
	mu.Lock()
	defer mu.Unlock()
	reader := curHandle
	curHandle++
	handleMap[reader] = r
	return reader
}

func getReader(reader C.reader) *reader {
	mu.Lock()
	defer mu.Unlock()
	return handleMap[reader]
}

func removeReader(reader C.reader) *reader {
	mu.Lock()
	defer mu.Unlock()
	r := handleMap[reader]
	delete(handleMap, reader)
	return r
}

func addWriter(w *writer) C.writer {
	mu.Lock()
	defer mu.Unlock()
	writer := curWriterHandle
	curWriterHandle++
	writerMap[writer] = w
	return writer
}

func getWriter(writer C.writer) *writer {
	mu.Lock()
	defer mu.Unlock()
	return writerMap[writer]
}

func removeWriter(writer C.writer) *writer {
	mu.Lock()
	defer mu.Unlock()
	w := writerMap[writer]
	delete(writerMap, writer)
	return w
}