BIG阳
我进行了一个 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 20volatile 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.gopackage 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]stringvar count int32var mtx sync.Mutex//export threadedCallbackfunc 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") } }}