I have shared library which provides a function that will go to waiting state during processing. The waiting is achieved by the condition variable provided by c++. Any one knows how to call this function correctly from Go?
C++ functions:
I have a queue to store all the tasks to be processed.
queue<Task> tasks;
Mutex mutex;
condition_variable cv;
void process(string img_path) {
std::unique_lock<Mutex> lock(mutex);
Task task(img_path);
tasks.push_back(task);
cv.wait(); //wait the task to be processed, because i have to process the tasks in a batch way using GPU
}
The above code is just used to illustrate the key component which is the blocking wait function of condition variable. It will be compiled into a dynamic library. If called from Python, I found a solution illustrated in here. Any one knows how to call from Golang?
I think your problem boils down to cgo
and the condition variable is just obscuring things. As a tiny demonstration of what you can do, consider a go program and a library built from a C++ file.
package main
// #cgo LDFLAGS: func.so
// void someFunc();
import "C"
import (
"fmt"
"time"
)
func main() {
fmt.Printf("Before C stuff.
")
t0 := time.Now()
C.someFunc()
fmt.Printf("%v
", time.Now().Sub(t0))
}
And now the C++ file:
#include <iostream>
#include <unistd.h>
extern "C" {
void someFunc();
}
void someFunc() {
sleep(10);
std::cout << "And print something
";
}
Build it and run it like this:
% g++ -Wall -Wextra -o func.o -c func.cc -fPIC
% gcc -Wall -Wextra -o func.so -shared func.o
% go build
% LD_LIBRARY_PATH=. ./cgofun
Before C stuff.
And print something
10.000273351s
Using the same technique you should be able to call a function that blocks on a condition variable. The go runtime won't care and will keep the calling goroutine blocked for as long as necessary.