c - C 中的同步回调

标签 c sockets callback android-source

我在 C DoSomething1(), DoSomething2(), ..., DoSomethingN() 中有多个方法请求一些数据.这些方法可以同时调用。 数据驻留在不同的进程中,目前当前进程与其他进程之间的通信是使用套接字完成的。

我如何创建同步回调 GetSpecialValue(),它使用上述套接字请求数据,然后当套接字回复时,将答案返回给特定的 DoSomethingN() 有请求吗?

请记住,我有很多方法使用单个套接字并传递请求,它们的回复应该返回到启动调用的特定方法。这些方法在不同的线程中工作。

int DoSomethingN(int id) {
    int returnValue = GetSpecialValue(id);
    return returnValue;
}

int GetSpecialValue(int id) {
    SendToProcessViaSocket(id);
    int returnValue = ReceiveSocketAnswer();
    return returnValue;
}

我知道有些人使用 libevent 进行回调,但我不认为您可以在调用事件时返回新参数。此外,它是异步的,不属于 AOSP 构建..

谢谢!

最佳答案

解决方案是在请求通过后锁定线程 然后,将锁添加到处理请求套接字的线程可见的 vector 。

std::tuple<int, pthread_mutex_t *, pthread_cond_t *, bool *> callbackData;
pthread_mutex_t *reqMutexLock = (pthread_mutex_t *)malloc(sizeof(*reqMutexLock));
pthread_cond_t *reqCondition = (pthread_cond_t *)malloc(sizeof(*reqCondition));
bool *state = (bool *)malloc(sizeof(*state));

(*reqMutexLock) = PTHREAD_MUTEX_INITIALIZER;
(*reqCondition) = PTHREAD_COND_INITIALIZER;
(*state) = false;

int callbackId = rand();

callbackData = std::make_tuple(callbackId, reqMutexLock, reqCondition, state);

pthread_mutex_lock(reqMutexLock);
SendRequest(callbackId, id);
while (!(*state)) {
    pthread_cond_wait(reqCondition, reqMutexLock);
}
pthread_mutex_unlock(reqMutexLock);
pthread_mutex_destroy(reqMutexLock);
free(reqMutexLock);
free(reqCondition);
...

当响应从套接字返回时, 响应将保存在响应 vector 中,并从 vector 中获取并释放锁。

...
response = ReceiveResponse();
responsesList.push_back(response);

...
reqMutexLock = std::get<1>(callbackDataList[foundIndex]);
reqCondition = std::get<2>(callbackDataList[foundIndex]);
state = std::get<3>(callbackDataList[foundIndex]);

pthread_mutex_lock(reqMutexLock);
(*state) = true;
pthread_cond_broadcast(reqCondition);
pthread_mutex_unlock(reqMutexLock);
...

锁释放后,线程会继续请求结果,结果会从vector中返回。

...
return GetResponse(callbackId);

关于c - C 中的同步回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39892187/

相关文章:

ios - Swift 中的回调函数语法

ios - 使用通知作为回调有问题吗?

c - 从 float 和 double 中读取一个文件?

iphone - 通过socket.h调用connect()时,使用GSoap返回EHOSTUNREACH

c - 通过已建立的 TCP 连接下载时检测 CRL 文件的结尾

java - 检测连接到我的网络的设备

ruby-on-rails - 如何修复此 before_destroy 回调 [rails]

c - 打印指向不带括号的矩阵的指针

c - 在哪里放置强大数字的声明?

objective-c - 如何在越狱的 iOS 设备上监控应用程序的 API 调用?