c - 使用一个参数调用 pthread_join 会导致分段错误?
问题描述
如果我连续调用 pthread_join (不使用其他函数),它将导致分段错误。
我可以通过在 pthread_join 的两个调用之间插入一个sleep();
,或其他任何东西来解决这个问题。printf()
操作系统和 GCC 版本:
gcc --version
gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
编译命令:
gcc demo_thread.c -lpthread -o demo_thread.out
源代码(demo_thread.c):
#include <stdio.h>
#include <stdlib.h>
void *f1(void *);
int main() {
int k = 2;
pthread_t fa[k];
for(int i=0; i<k; i++) {
pthread_create(&fa[i], NULL, f1, NULL);
}
for(int i=0; i<k; i++) {
// printf("%ul\n", fa[i]); // uncomment this line, problem disapper.
pthread_join(fa[i]);
}
}
void *f1(void *arg) {
for(int i=0; i<4;i++) {
printf("%d\n",i );
}
return 0;
}
解决方案
你是怎么编译的?我刚刚意识到您没有使用#include <pthread.h>
并且您使用了一个参数而不是两个 for pthread_join
。
如果我遗漏了我得到的包含
error: unknown type name ‘pthread_t’
如果我确实包含它,那么我会得到
error: too few arguments to function ‘pthread_join’
哦,我明白了,如果我包含#include <stdlib.h>
并省略,<pthread.h>
那么它将有一个定义,pthread_t
但没有pthread_join
。但是仍然有很多警告:
warning: implicit declaration of function ‘pthread_join’
-Wall -W -pedantic
您应该始终使用编译器的参数构建程序。并修复警告。
并解释崩溃:由于您没有将 NULL 作为第二个参数传递给pthread_join
它将接收“随机”值,然后将其写入它,就好像它是一个指针一样。它不是。所以它要么将一个值写入你不应该分配的内存中,要么会出现分段错误。
并解释如何printf
或sleep
解决问题:进行这些函数调用必须更改RSI
寄存器的值(RSI 用于第二个函数参数),使其成为有效指针或 NULL。
推荐阅读
- pine-script - Pine Script Multi Time Frame - 我的策略是重新粉刷,但我不知道为什么
- firebase - Firestore 安全规则 - 未找到函数存在
- wagtail-admin - 如何禁用 wagtail 主页和侧面菜单上的用户名和电子邮件显示?
- swift - 如何在 SwiftUI 中制作 struct LazyList?
- android - TextView 背景不会正确换行
- javascript - 验证 ReactJS 密码确认
- c# - C# Mongodb - 仅获取文档的指定字段
- php - 我将使用 laravel 5.6,安装 composer 时出现此错误,我该怎么办?
- wordpress - 缺少网站的 Facebook 分享按钮
- javascript - 如何捕获或记录对角鼠标移动?