gpt4 book ai didi

C++:将结构传递给 PThread

转载 作者:太空狗 更新时间:2023-10-29 20:39:35 24 4
gpt4 key购买 nike

所以我试图通过使用结构将多个值传递给线程。

这是我的:

int main()
{

struct Data
{
int test_data;
int test_again;
};

Data data_struct;
data_struct.test_data = 0;
data_struct.test_again = 1;

pthread_create(&thread, NULL, Process_Data, (void *)&data_struct);
return 0;
}


void* Process_Data(void *data_struct)
{
struct test
{
int test_variable;
int test_two;
};
test testing;
testing.test_variable = *((int *)data_struct.test_data);
testing.test_two = *((int *)data_struct.test_again);
}

为了简单起见,我省略了任何代码(包括 #include 和 thrad 连接等)我认为对于这个问题来说是不必要的,但是如果需要更多代码,请询问。

当只传递一个整数变量时,线程工作正常。

这是我遇到的错误:

在函数“void* Process_Data(void*)”中:错误:请求“data_struct”中的成员“test_variable”是非类类型“void*”testing.test_variable = *((int *)data_test.测试变量);

其他变量也一样

提前感谢您的任何建议。

最佳答案

通常的做法是

void* Process_Data(void *data_struct)
{
Data *testing = static_cast<Data*>(data_struct);

// testing->test_data and testing->test_again are
// data_struct.test_data and data_struct.test_again from main
}

你得到你得到的错误是因为你试图从一个没有任何成员的 void 指针中挑选成员。为了使用您知道 void 指针指向的结构,您必须将其强制转换回指向该结构的指针。

另外,请注意,您应该pthread_join您刚刚启动的线程,否则 main 将在它可以执行任何操作之前结束。

关于C++:将结构传递给 PThread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27488820/

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