如何解决如何在 C 中跨多个线程重新分配?
我使用 malloc 创建了一个未定义大小的列表,它跟踪线程及其数据。但是,如果我在线程仍在运行时重新分配,它们将不再能够保存数据,因为结构的内存位置已更改。我的项目不断增加/减少线程,所以我需要重新分配。
代码:
#include <windows.h>
#include <stdio.h>
typedef struct option_data {
char* contract[3];
} option_data;
typedef struct thread_data {
char* thread;
} thread_data;
DWORD WINAPI optionSymbol(void* dat) {
option_data* data = (option_data*)dat;
data->contract[0] = 6;
data->contract[1] = 7;
data->contract[2] = 5;
return 0;
}
int create_thread(void* data,void* dat2) {
HANDLE thread = CreateThread(NULL,optionSymbol,data,NULL);
thread_data* t_data = (thread_data*)dat2;
t_data->thread = thread;
return 0;
}
void reallocation(lista,sizeOfList)
{
char** list = lista;
char* listThingy = realloc(*list,sizeOfList * sizeof * list);
if (listThingy == NULL)
free(listThingy);
else
*list = listThingy;
}
int getChains(void)
{
option_data* optionDataList = malloc(sizeof(option_data));
thread_data* threadDataList = malloc(sizeof(thread_data));
create_thread(&optionDataList[0],&threadDataList[0]);
//reallocation(&optionDataList,2)
//reallocation(*threadDataList,2) <-- The code returns unpredictably when un-noting these two lines.
create_thread(&optionDataList[0],&threadDataList[0]);
WaitForSingleObject(threadDataList[0].thread,INFINITE);
CloseHandle(threadDataList[0].thread);
printf("%i",optionDataList[0].contract[0]);
return 0;
}
int main()
{
getChains();
return 0;
}
如何在不更改结构的原始内存位置或将新内存位置发送给线程的情况下重新分配?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。