【问题标题】:Passing a vector of objects to pthread_create [duplicate]将对象向量传递给 pthread_create [重复]
【发布时间】:2017-05-05 02:03:21
【问题描述】:

如何将对象向量传递给 pthread_create 函数?

我有这个代码:

#define THREAD_NUMBER 1000

void* threadRoom (std::vector <Room*> &rooms){

some code here....
}

int main () {

std::vector <Room*> rooms;
std::vector <pthread_t> workers(THREAD_NUMBER);
pthread_create(&workers[0], NULL, threadRoom, &rooms);

return 0;
}

我收到以下错误:

error: invalid conversion from ‘void* (*)(std::vector<Room*>&)’ to ‘void* (*)(void*)’ [-fpermissive]
pthread_create(&worker[0], NULL, threadRoom, &rooms);

note: initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’
extern int pthread_create (pthread_t *__restrict __newthread

【问题讨论】:

  • 您将指向rooms 的指针传递给pthread_create,但您的threadRoom 函数需要引用。

标签: c++ multithreading vector pthreads parameter-passing


【解决方案1】:

嗯,是的。 pthread_create() 要求其第三个参数的类型为 void* (*)(void *),而您传递的参数类型为 void* (*)(std::vector&lt;Room*&gt;&amp;)。这些不兼容。你的线程函数声明的参数类型必须是void *

您可以将实际(指针)参数转换为类型void *,并让threadRoom() 将其转换回预期类型。这不是类型安全的,但实际上是预期的用法(尽管它是 C API,并且 C 不需要强制转换)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多