繁体   English   中英

调用pthread_create()C ++ Linux时出现段错误

[英]segfault when calling pthread_create() c++ linux

没来过一阵子,但我被卡住了...我似乎无法弄清楚这段代码的出处在哪里

logger.cpp

#include "logger.h"
#include <unistd.h>
#include <stdlib.h>

void* __logger(void* data)  // dummy function
{
    sleep(10);
    return NULL;
}

logger_t::logger_t()
{
    // create a pipe for communicating with thread
    if (pipe(fd) == -1) // something went wrong
    {
        // error here
        exit(EXIT_FAILURE);
    }
    // now create the thread that will write to the log
    if (pthread_create(log_pid, NULL, &__logger, NULL))  // something went wrong
    {
        exit(EXIT_FAILURE);
    }
}

logger_t::~logger_t()
{
    close(fd[1]);     // close read end of pipe, logging thread will read EOF and exit
    if (pthread_join(*log_pid, NULL))
    {
        exit(EXIT_FAILURE);
    }
}

logger.h

#ifndef LOGGER_H
#define LOGGER_H
#include <pthread.h>

class logger_t
{
    public:
        logger_t();
        ~logger_t();

    private:
        int fd[2];
        pthread_t* log_pid;
};
#endif // LOGGER_H

main.cpp

#include "logger.h"

int main()
{
    logger_t proglog;
    return 0;
}

代码可以很好地编译,但是当我运行它时,在pthread_create()调用期间出现了段错误...有什么想法吗? 我已经剥离了程序中的所有内容,但仍然遇到相同的崩溃...

pthread_create()的手册页中:

返回之前,对pthread_create()的成功调用将新线程的ID存储在线程指向的缓冲区中。

thread参数应该指向有效的东西-在您的情况下,您传入的是未初始化的指针。 也许这与它有关。 要确认,请在调试器(例如gdb)中运行它,然后看一下。

另外,正如您指出的是c ++一样,您应该真正使用std::thread()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM