我有一个共享库,它提供了一个在处理过程中进入等待状态的函数。等待是通过c++提供的条件变量实现的。谁知道如何从 Go 中正确调用此函数?
C++ 函数:
我有一个队列来存储所有要处理的任务。
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
}
上面的代码只是用来说明其中的关键部分,即条件变量的阻塞等待函数。它将被编译成一个动态库。如果从 Python 调用,我找到了 here 中说明的解决方案.谁知道如何从 Golang 调用?
最佳答案
我认为您的问题归结为 cgo
并且条件变量只是模糊的东西。作为您可以做什么的一个小演示,考虑一个 go 程序和一个从 C++ 文件构建的库。
package main
// #cgo LDFLAGS: func.so
// void someFunc();
import "C"
import (
"fmt"
"time"
)
func main() {
fmt.Printf("Before C stuff.\n")
t0 := time.Now()
C.someFunc()
fmt.Printf("%v\n", time.Now().Sub(t0))
}
现在是 C++ 文件:
#include <iostream>
#include <unistd.h>
extern "C" {
void someFunc();
}
void someFunc() {
sleep(10);
std::cout << "And print something\n";
}
像这样构建并运行它:
% 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
使用相同的技术,您应该能够调用阻塞条件变量的函数。 Go 运行时不会关心,只要有必要,它就会一直阻塞调用 goroutine。
关于multithreading - 共享库中的 block Go 例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37396207/