【发布时间】:2020-01-09 19:33:49
【问题描述】:
我在 C 中有一个带有 2 个管道和 2 个回调函数的 ALooper,
mainThreadLooper = ALooper_forThread(); // get looper for this thread
ALooper_acquire(mainThreadLooper); // add reference to keep object alive
pipe(messagePipe);
pipe(commandPipe);
ALooper_addFd(mainThreadLooper, messagePipe[0],
0, ALOOPER_EVENT_INPUT, looperCallback, NULL);
ALooper_addFd(mainThreadLooper, commandPipe[0],
0, ALOOPER_EVENT_INPUT, commandLooperCallback, NULL);
这里有两个可以正常工作的回调函数
static int commandLooperCallback(int fd, int events, void* data){
LOGD("command pipe callback");
wchar_t c;
read(fd, &c,sizeof(c));
if(running){
if(c == 0){
return 1;
}
if(c == CLEAR_SCREEN){
LOGD("clear screen");
clearScreen();
return 1;
}
}
return 1;
}
static int looperCallback(int fd, int events, void* data) {
//char msg[100];
wchar_t msg[100];
int length = read(fd, &msg,sizeof(msg)); //99); // read message from pipe
LOGD("string recieved: %ls", msg);
char str[length];
wcstombs(str,msg,length);
LOGD("char string %s", str);
//msg[length] = 0;
if(running){
printToTextView(str);
}
//LOGD("returning from looper callback");
return 1; // continue listening for events
}
问题是它们在我的代码中被乱序调用,导致clearScreen() 在与我在代码中写入管道时不同的时间。
如果有人知道如何同步这些 alooper 回调,请填写。我正在使用 ALooper,因为我在 C 中使用 pthread,并且对管道的写入发生在 pthread 中,而 Alooper 是我回调 UI 的方式android中的线程
感谢您的宝贵时间
【问题讨论】:
标签: c multithreading android-ndk pipe pthreads