1 回答
TA贡献1859条经验 获得超6个赞
我进行了一个 Go 回调的实验,从 20 个本地 Windows 线程并行调用。回调增加一个变量,将元素添加到地图并在屏幕上打印值。一切都很顺利,所以我认为在更复杂的场景中也不会出现问题。
这是我的测试的源代码供其他人使用:
代理.h
#ifndef _PROXY_H_
#define _PROXY_H_
long threaded_c_func(long param);
#endif
代理.c
#include "proxy.h"
#ifdef WIN32
#include <Windows.h>
#endif
#define ROUNDS 20
volatile long passed = 0;
extern long long threadedCallback(long cbidx);
DWORD WINAPI ThreadFunc(LPVOID param) {
threadedCallback(*((long *)param));
InterlockedIncrement(&passed);
}
long threaded_c_func(long cbidx) {
for (int i = 0; i < ROUNDS; i++)
{
DWORD ThreadId = 0;
CreateThread(NULL, 1024*1024, &ThreadFunc, (LPVOID) &cbidx, 0, &ThreadId);
}
while (passed < ROUNDS)
{
Sleep(100);
}
return ROUNDS;
}
回调Test.go
package main
/*
#cgo CFLAGS: -I .
#cgo LDFLAGS: -L .
#include "proxy.h"
long threaded_c_func(long param);
*/
import "C"
import (
"fmt"
"strconv"
"sync"
)
var hashTable map[int32]string
var count int32
var mtx sync.Mutex
//export threadedCallback
func threadedCallback(cbidx int) C.longlong {
mtx.Lock()
defer mtx.Unlock()
count++
hashTable[count] = strconv.Itoa(int(count))
fmt.Println("Current counter ", count)
return C.longlong(count)
}
func main() {
hashTable = make(map[int32]string)
var expected C.long
expected = C.threaded_c_func(1)
if int32(expected) == count {
fmt.Println("Counters match")
} else {
fmt.Println("Expected ", int32(expected), " got ", count)
}
for k, v := range hashTable {
if strconv.Itoa(int(k)) == v {
fmt.Println(v, " match")
} else {
fmt.Println(v, "don't match")
}
}
}
- 1 回答
- 0 关注
- 108 浏览
添加回答
举报