amu*_*cxg 4 c pthreads pthread-join
我目前正在开发一个使用pthreads的项目.到目前为止,该项目启动了用户指定的线程数,并在每个线程上执行一些工作然后关闭.每个线程都存储在动态分配的内存数组中.我这样做使用:
threads = malloc(number_of_threads * sizeof(pthread_t));
然后我在for循环中创建每个线程:
pthread_create(&(threads[i]), NULL, client_pipe_run, (void *) ¶m[i]);
Run Code Online (Sandbox Code Playgroud)
我接下来需要做的是存储这些线程的返回值.我的理解是我需要将pthread_join传递给我想要存储返回值的指针的地址.这是我有点困惑的地方.到目前为止我的指针很好,然后我的大脑有一种融化的哈哈.这是我如何实现这一点的想法,但我不相信这是正确的:
int *return_vals = malloc(sizeof(int) * number_of_threads);
for(i = 0; i< number_of_threads; i++)
{
pthread_join(&(threads[i]),(void *) &(return_vals[i]));
}
Run Code Online (Sandbox Code Playgroud)
然后为了得到返回值,我会做类似的事情:
int val = *(return_val[0]);
Run Code Online (Sandbox Code Playgroud)
任何有关这方面的帮助将不胜感激!
请注意,您正在为线程分配内存,如下所示:
threads = malloc(number_of_thread * sizeof(pthread_t));
Run Code Online (Sandbox Code Playgroud)
但对于返回值,您可以:
int *return_vals = malloc(sizeof(int *));
Run Code Online (Sandbox Code Playgroud)
也就是说,在这里也应该计算线程数:
int *return_vals = malloc(number_of_thread * sizeof(int));
Run Code Online (Sandbox Code Playgroud)
然后你可以将返回值强制转换为void*:
void *foo(void *arg) {
int i = 7;
return (void*)i;
}
int main(void) {
int i = 0;
int thread_count = 3;
pthread_t* threads = malloc(thread_count * sizeof(pthread_t));
int *return_vals = malloc(thread_count * sizeof(int));
// create threads:
for(i = 0; i < thread_count; ++i)
pthread_create(&threads[i], NULL, &foo, NULL);
// wait untill they finish their work:
for(i = 0; i < thread_count; ++i)
pthread_join(threads[i], (void**) &return_vals[i]);
// print results:
for(i = 0; i < thread_count; ++i)
printf("Thread %d returned: %d\n", i, return_vals[i]);
// clean up:
free(return_vals);
free(threads);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
或者你可以确保你的代码没有对你返回的类型的大小做出任何假设,或者sizeof(void*)在线程中动态地为返回值分配内存:
void *foo(void *arg) {
int* ret = malloc(sizeof(int));
*ret = 7;
return ret;
}
int main(void) {
int i = 0;
int thread_count = 3;
pthread_t* threads = malloc(thread_count * sizeof(pthread_t));
// array of pointers to return values of type int:
int **return_vals = calloc(thread_count, sizeof(int*));
// create threads:
for(i = 0; i < thread_count; ++i)
pthread_create(&threads[i], NULL, &foo, NULL);
// wait untill they finish their work:
for(i = 0; i < thread_count; ++i)
pthread_join(threads[i], (void**) &return_vals[i]);
// print results:
for(i = 0; i < thread_count; ++i)
printf("Thread %d returned: %d\n", i, *return_vals[i]);
// clean up:
for(i = 0; i < thread_count; ++i)
free(return_vals[i]);
free(return_vals);
free(threads);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是如果您选择后者,请注意可能最终导致的内存泄漏.
| 归档时间: |
|
| 查看次数: |
7435 次 |
| 最近记录: |