2020-11-28 20:07:58 +08:00
|
|
|
// Copyright (c) 2020 Meng Huang (mhboy@outlook.com)
|
|
|
|
// This package is licensed under a MIT license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package sem
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/hslam/ftok"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestSem(t *testing.T) {
|
|
|
|
done := make(chan struct{})
|
2020-11-30 17:57:40 +08:00
|
|
|
semnum := 0
|
|
|
|
nsems := 1
|
2020-11-28 20:07:58 +08:00
|
|
|
go func() {
|
|
|
|
key, err := ftok.Ftok("/tmp", 0x22)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2020-11-30 17:57:40 +08:00
|
|
|
semid, err := Get(key, nsems, 0666)
|
2020-11-28 20:07:58 +08:00
|
|
|
if err != nil {
|
2020-11-30 17:57:40 +08:00
|
|
|
semid, err = Get(key, nsems, IPC_CREAT|IPC_EXCL|0666)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
defer Remove(semid)
|
|
|
|
for semnum := 0; semnum < nsems; semnum++ {
|
|
|
|
_, err := SetValue(semid, semnum, 1)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|
2020-11-28 20:07:58 +08:00
|
|
|
}
|
2020-11-30 17:57:40 +08:00
|
|
|
ok, err := P(semid, semnum, IPC_NOWAIT|SEM_UNDO)
|
2020-11-28 20:07:58 +08:00
|
|
|
if err != nil {
|
|
|
|
t.Error(err)
|
|
|
|
}
|
|
|
|
if !ok {
|
|
|
|
t.Error("P failed!\n")
|
|
|
|
}
|
|
|
|
time.Sleep(time.Millisecond * 200)
|
2020-11-30 17:57:40 +08:00
|
|
|
ok, err = V(semid, semnum, IPC_NOWAIT|SEM_UNDO)
|
2020-11-28 20:07:58 +08:00
|
|
|
if err != nil {
|
|
|
|
t.Error(err)
|
|
|
|
}
|
|
|
|
if !ok {
|
|
|
|
t.Error("V failed!\n")
|
|
|
|
}
|
|
|
|
time.Sleep(time.Millisecond * 100)
|
|
|
|
close(done)
|
|
|
|
}()
|
|
|
|
time.Sleep(time.Millisecond * 100)
|
|
|
|
key, err := ftok.Ftok("/tmp", 0x22)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2020-11-30 17:57:40 +08:00
|
|
|
semid, err := Get(key, nsems, 0666)
|
2020-11-28 20:07:58 +08:00
|
|
|
if err != nil {
|
2020-11-30 17:57:40 +08:00
|
|
|
t.Error()
|
2020-11-28 20:07:58 +08:00
|
|
|
}
|
2020-11-30 17:57:40 +08:00
|
|
|
if r, err := GetValue(semid, semnum); err != nil {
|
2020-11-28 20:07:58 +08:00
|
|
|
panic(err)
|
|
|
|
} else if r > 0 {
|
|
|
|
t.Error()
|
|
|
|
}
|
2020-11-30 17:57:40 +08:00
|
|
|
ok, err := P(semid, semnum, IPC_NOWAIT|SEM_UNDO)
|
2020-11-28 20:07:58 +08:00
|
|
|
if err != nil {
|
|
|
|
t.Error(err)
|
|
|
|
}
|
|
|
|
if ok {
|
|
|
|
t.Error()
|
|
|
|
}
|
|
|
|
<-done
|
|
|
|
}
|