【发布时间】:2022-01-04 15:57:53
【问题描述】:
对于学校,我正在从事一个项目,该项目有 2 个正在运行的读取线程和 1 个围绕共享缓冲区工作的写入线程。这个共享缓冲区是我们自己编程的某种基于指针的列表。为了使其线程安全,我使用了 pthread_rw_locks 和一些 pthread_barriers。当我尝试运行我的代码时,它几乎立即崩溃,并且给了我一个分段错误。使用 gdb 调试器时,它给了我以下消息:
程序收到信号 SIGSEGV,分段错误。
__pthread_barrier_init (barrier=0x0, attr=0x0, count=2) 在 pthread_barrier_init.c:47
47 pthread_barrier_init.c: 没有这样的文件或目录。
在编译时,我包含了 -lpthread 标志,并且我还确保在使用它的每个文件中都包含 pthread.h。知道为什么我的程序找不到这个 c 文件吗?
编辑
这是我使用的代码的 sn-p。 (这几乎是所有代码,但在这部分出错了)
这是我的主循环代码
int main(int argc, char*argv[])
{
sbuffer_t* buffer;
sbuffer_init(&buffer);
return 0;
}
这是我的缓冲区代码
/**
* basic node for the buffer, these nodes are linked together to create the buffer
*/
typedef struct sbuffer_node {
struct sbuffer_node *next; /**< a pointer to the next node*/
sensor_data_t data; /**< a structure containing the data */
} sbuffer_node_t;
/**
* a structure to keep track of the buffer
*/
struct sbuffer {
sbuffer_node_t *head; /**< a pointer to the first node in the buffer */
sbuffer_node_t *tail; /**< a pointer to the last node in the buffer */
pthread_rwlock_t* lock;
pthread_barrier_t* barrierRead; //Barrier to indicate that both reader threads have succesfully read the sensor reading
pthread_barrier_t* barrierWrite; //Barrier to indicate that a sensor reading has been removed
pthread_mutex_t* FIFOlock;
int finished;
};
int sbuffer_init(sbuffer_t **buffer) {
(*buffer) = malloc(sizeof(sbuffer_t));
(*buffer)->lock=malloc(sizeof(pthread_rwlock_t));
if (*buffer == NULL) return SBUFFER_FAILURE;
pthread_rwlock_init((*buffer)->lock,NULL);
pthread_rwlock_wrlock((*buffer)->lock);
pthread_barrier_init((*buffer)->barrierRead, NULL, READER_THREADS);
pthread_barrier_init((*buffer)->barrierWrite, NULL, READER_THREADS);
pthread_mutex_init((*buffer)->FIFOlock, NULL);
(*buffer)->head = NULL;
(*buffer)->tail = NULL;
(*buffer)->finished = CONNMGR_NOT_FINISHED;
pthread_rwlock_unlock((*buffer)->lock);
return SBUFFER_SUCCESS;
}
【问题讨论】:
-
No such file or directory错误消息只是说您没有可用的 pthread 源代码,因此调试器无法显示发生分段错误的源代码行。这与您的程序的执行无关。它不需要文件即可运行。分段错误的原因在于您编写的代码中,在调试器中查看pthread_barrier_init.c内容并没有多大帮助。只需在 gdb 中up几次,直到您在编写的代码中到达一个框架,gdb 应该能够显示其源代码。 -
Re "错误在你写的代码中",是的,很明显。调试器显示
0(x86/x86-64 上的NULL)被传递给barrier参数。 -
如果您想询问分段错误的原因,您应该将导致错误的minimal reproducible example 编辑到问题中并询问该问题。如果您出于某种原因确实想查看该源文件,则需要安装源,详细信息将取决于您的操作系统/发行版。
-
但是当我调用 pthread_barrier_init() 函数时会发生分段错误。在此之后它崩溃并给出找不到该函数的c文件的错误。所以看起来我的程序必须能够找到这个c文件?
-
你认为
pthread_barrier_t* barrierRead指向什么?
标签: c linux pthread-barriers