创建动态 pthread_t 时出错
Error when creating dynamic pthread_t
我正在尝试动态创建 pthread 并面临变量寻址问题。你能告诉我应该如何访问地址吗
int main (int argc, char *argv[])
{
pthread_t *threads;
int rc, numberOfThreads;
long t;
cout<<"Number of Threads = ";
cin>>numberOfThreads;
cout<<endl;
threads =(pthread_t*) malloc(numberOfThreads*sizeof(pthread_t));
for(t=0; t<numberOfThreads; t++){
printf("In main: creating thread %ld\n", t);
// **ERROR ON BELOW LINE**
rc = pthread_create((pthread_t)&(threads+numberOfThreads), NULL, FunctionForThread, (void *)t);
(void) pthread_join(threads[t], NULL);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
错误 : lvalue required as unary ‘&’ operand
pthread_create() 需要 pthread_t*
类型作为第一个参数。您有一个 pthread_t
数组,因此传递其中一个的地址:
rc = pthread_create(&threads[i], NULL, FunctionForThread, (void *)t);
另请注意,强制转换 (void *)t
不正确。您应该传递一个指向有效对象的指针。
我正在尝试动态创建 pthread 并面临变量寻址问题。你能告诉我应该如何访问地址吗
int main (int argc, char *argv[])
{
pthread_t *threads;
int rc, numberOfThreads;
long t;
cout<<"Number of Threads = ";
cin>>numberOfThreads;
cout<<endl;
threads =(pthread_t*) malloc(numberOfThreads*sizeof(pthread_t));
for(t=0; t<numberOfThreads; t++){
printf("In main: creating thread %ld\n", t);
// **ERROR ON BELOW LINE**
rc = pthread_create((pthread_t)&(threads+numberOfThreads), NULL, FunctionForThread, (void *)t);
(void) pthread_join(threads[t], NULL);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
错误 : lvalue required as unary ‘&’ operand
pthread_create() 需要 pthread_t*
类型作为第一个参数。您有一个 pthread_t
数组,因此传递其中一个的地址:
rc = pthread_create(&threads[i], NULL, FunctionForThread, (void *)t);
另请注意,强制转换 (void *)t
不正确。您应该传递一个指向有效对象的指针。