calling back and forth of C++ and go functions

74 views
Skip to first unread message

sudars...@gmail.com

unread,
Aug 26, 2019, 1:48:14 PM8/26/19
to golang-nuts
Hi, 
I am planning to replace C++ threadpool class with goroutines. I see several go implementations for threadpool. 

few are 

I am having issue, when i need to call back and forth . preferably, I need to keep C++ function has main. C++ function calls SubmitTask. Go library should call run with the ID i passed to SubmitTask.

Please let me know reference or links which could help me. 



// main.go

import "C"
func SubmitTaskHandler(workitem interface{}) {
    itemid := workitem.(int32)
    fmt.Println(itemid)
    tmp := C.int(itemid)
    C.run(tmp)
}
//export SubmitTask
func SubmitTask( x int32) {
    fmt.Println("GO called from C ")
    _ = pool.Invoke(int32(x))
}

func main() {
    defer ants.Release()
    var runTimes int32 = 1000
        for i := int32(0); i < runTimes; i++ {
            go SubmitTask(i)
        }

    fmt.Scanln()
        fmt.Println("done")
        fmt.Printf("running goroutines: %d\n", ants.Running())
        fmt.Printf("finish all tasks.\n")

}



test.c file:
#include "_cgo_export.h"
void submittask(int i)
{
    SubmitTask(i);
}


Regards,

Ian Lance Taylor

unread,
Aug 26, 2019, 1:57:49 PM8/26/19
to sudars...@gmail.com, golang-nuts
On Mon, Aug 26, 2019 at 10:48 AM <sudars...@gmail.com> wrote:
>
> I am planning to replace C++ threadpool class with goroutines. I see several go implementations for threadpool.

Without getting into how to do this, why do you want to do this?
Goroutines work very well for Go code, but when Go code calls into C++
code, it uses up a thread. The Go scheduler support for multiplexing
goroutines onto threads does not work for goroutines that call into
C++ (or any other non-Go language). So I don't think you will get any
advantage by using goroutines instead of a C++ threadpool to run C++
code.

Ian

sudars...@gmail.com

unread,
Aug 27, 2019, 1:00:10 PM8/27/19
to golang-nuts
Thanks Ian for the inputs. I was trying to migrate our CPP application to GO in a phased manner. 
I thought of first plugging out the threadpool and replace it with GO's implementation. 
I understand the approach is not correct , instead plugging out partial functionality from CPP application and making a seperate GO 
microservice might give some improvements. 

Regards,
Reply all
Reply to author
Forward
0 new messages