c - pthread_join 不断导致段错误
问题描述
这个问题绝对是一个愚蠢错误的根源,但对于我的生活,我无法深入了解它。
我正在编写一个更大的程序,但我已经缩小了每当我调用pthread_join
. 我在下面包含了相关代码,希望有人可以帮助我找出我做错了什么。干杯:)
用于管理 pthread 的函数
void *scalloc(size_t nmemb, size_t size)
{
void *p;
p = calloc(nmemb, size);
if (p == NULL)
sys_error("Error allocating memory block (calloc).", 1);
return p;
}
pthread_t *new_thread_array(int n)
{
return scalloc(n, sizeof(pthread_t));
}
int spthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg)
{
int ret;
if ((ret = pthread_create(&thread, attr, start_routine, arg)) != 0)
sys_error("Error at pthread_create.", ret);
return 0;
}
int spthread_join(pthread_t thread, void **retval)
{
int ret;
if ((ret = pthread_join(thread, retval)) != 0)
sys_error("Error at pthread_join.", ret);
return 0;
}
int create_threads(pthread_t *thread_arr, int n, const pthread_attr_t *attr,
void *(*start_routine) (void *), void **arg_arr)
{
for (int i = 0; i < n; i++) {
spthread_create(&thread_arr[i], attr, start_routine, arg_arr[i]);
debug("created thread %d", i);
}
return 0;
}
int join_threads(pthread_t *thread_arr, int n, void **ret_arr)
{
debug("Starting join");
for (int i = 0; i < n; i++) {
if (ret_arr != NULL)
spthread_join(thread_arr[i], ret_arr[i]);
else {
debug("Attempting to join %d", i);
spthread_join(thread_arr[i], NULL);
debug("Joined %d", i);
}
}
return 0;
}
产生错误的测试代码
void *threadfunc(void *id)
{
fflush(stdout);
fprintf(stdout, "Thread %d printing.\n", *(int *)id);
fflush(stdout);
return;
}
int threadtest(int nodes)
{
int ret;
int *targs = scalloc(nodes, sizeof(int));
int *pass[nodes];
for (int i = 0; i < nodes; i++) {
targs[i] = i;
pass[i] = &targs[i];
}
printf("Starting L1 thread test...\n");
pthread_t *threads = new_thread_array(nodes);
debug("Allocated pthread array for %i threads.", nodes);
create_threads(threads, nodes, NULL, &threadfunc, pass);
join_threads(threads, nodes, NULL);
debug("Successfully joined %i threads.", nodes);
free(targs);
free(threads);
return 0;
}
int main()
{
return threadtest(5);
}
最后,这是运行函数的输出threadtest
,确认段错误(出现)发生在父线程中,在调用pthread_join
.
Starting L1 thread test...
Allocated pthread array for 5 threads.
created thread 0
created thread 1
Thread 0 printing.
created thread 2
Thread 1 printing.
Thread 2 printing.
created thread 3
Thread 3 printing.
created thread 4
Thread 4 printing.
Starting join
Attempting to join 0
zsh: segmentation fault ./tests/L1tests
解决方案
推荐阅读
- amazon-web-services - 运行多个 apache spark 流作业
- deep-learning - 为 PyTorch 模型在 GPU 之间安排作业
- rabbitmq - 有没有办法将nestjs cqrs 与rabbitmq 事件总线/队列一起使用。从命令中分派由微服务处理的事件是反模式吗?
- python - 单个位置索引器超出范围错误
- python - 用浮点数拆分列并在新列中添加整数和小数部分
- typescript - 使用子节点数据检索另一个用户 UID
- c# - 使用 LINQ 将 DataTable 转换为嵌套对象
- python - NameError:名称“regc”未在 Tkinter 中定义
- java - 如何在 Java 中测试不同的“表格输入”?
- typescript - 按聚合列排序