将对象向量传递给pthread_create

时间:2016-12-19 23:05:41

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

如何将对象向量传递给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

1 个答案:

答案 0 :(得分:0)

是的。 pthread_create()要求其第三个参数具有类型void* (*)(void *),并且您传递的类型为void* (*)(std::vector<Room*>&)。这些不兼容。线程函数的声明参数类型必须为void *

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