-
Notifications
You must be signed in to change notification settings - Fork 21
/
gmagick.go
95 lines (80 loc) · 1.66 KB
/
gmagick.go
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package gmagick
/*
#cgo !no_pkgconfig pkg-config: GraphicsMagickWand
#include <wand/wand_api.h>
*/
import "C"
import (
"runtime"
"sync"
"sync/atomic"
)
var (
initOnce sync.Once
terminateOnce *sync.Once
// Indicates that terminate method can be called (there are no any ImageMagick objects)
canTerminate = make(chan struct{}, 1)
envSemaphore = make(chan struct{}, 1)
// Ref counters
magickWandCounter int64
drawingWandCounter int64
pixelWandCounter int64
)
// Initializes the MagickWand environment
func Initialize() {
envSemaphore <- struct{}{}
defer func() {
<-envSemaphore
}()
initOnce.Do(func() {
C.InitializeMagick(nil)
terminateOnce = &sync.Once{}
setCanTerminate()
})
}
// Terminates the MagickWand environment
// wait until all imageMagick objects destroyed
func Terminate() {
envSemaphore <- struct{}{}
defer func() {
<-envSemaphore
}()
if terminateOnce != nil {
terminateOnce.Do(func() {
runtime.GC()
terminate()
})
}
}
func terminate() {
<-canTerminate
C.DestroyMagick()
initOnce = sync.Once{}
}
// Set status "terminate can be called"
func setCanTerminate() {
if isImageMagickCleaned() {
select {
case canTerminate <- struct{}{}:
// Now we can terminate
default:
// Nothing to do
}
}
}
// Set status "terminate can`t be called"
func unsetCanTerminate() {
select {
case <-canTerminate:
// Now we can`t terminate
default:
// Nothing to do
}
}
// Check are all IM objects are collected by GC
func isImageMagickCleaned() bool {
if atomic.LoadInt64(&magickWandCounter) != 0 || atomic.LoadInt64(&drawingWandCounter) != 0 || atomic.LoadInt64(&pixelWandCounter) != 0 {
return false
}
return true
}