gpt4 book ai didi

ios - 混合 GCD 和 pThread 会导致奇怪的效果

转载 作者:行者123 更新时间:2023-11-29 02:16:23 27 4
gpt4 key购买 nike

我已经下载了一个我想使用的多平台库。该库在构建纯 C 命令行应用程序时运行良好。整个 printfs 完全显示了我的预期。

我是这样从 iOS Objective-C 调用它的:

dispatch_async() { 
callbackFunctPtr = myCallBackFunction;
LibrariesRunLoopFunction();
}

库开始运行并执行导致 C 代码中的 pthread_create()s 的操作,然后回调如下:

void myCallBackFunction(char *text)
{

NSLog( @"%s", __PRETTY_FUNCTION__ );
dispatch_async( dispatch_get_main_queue(), ^{
// This line seems to get called sometimes once, sometimes many times.
[myViewControllerPtr updateUITextViewWith:text];
}

}

我无法理解的是 [myViewControllerPtr updateUITextViewWith:text];似乎有时被调用一次但经常被调用多次,有时文本损坏。

最佳答案

跨线程传递 char* C 字符串时,内存管理几乎是不可能的。你不知道谁创建了内存,也不知道接收者何时会用完它以便你可以释放它。

我的猜测是传递给 myCallBackFunction 的 char * 文本仅在调用期间有效,并在函数返回后立即释放。 (它可能是通过 malloc() 分配的,并通过调用 free() 释放的。)

您将需要想出一些方法来管理不同线程之间的内存。

一种方法是在回调函数中复制字符串,然后在完成后将其从主线程中释放:

void myCallBackFunction(char *text)
{
//Create a block of memory for the string copy (plus 1 for the null)
char *newText = malloc(strlen(text)+1);

//Copy the string to the newly allocated buffer.
strcpy(newText, text);
NSLog( @"%s", __PRETTY_FUNCTION__ );
dispatch_async( dispatch_get_main_queue(), ^{
// This line seems to get called sometimes once, sometimes many times.
[myViewControllerPtr updateUITextViewWith:newText];
//free the text buffer once the view controller is done with it.
free(newText);
}
}

关于ios - 混合 GCD 和 pThread 会导致奇怪的效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28707587/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com