我在执行以下示例程序时遇到分段错误:
#include<iostream>
#include<pthread.h>
#include<string.h>
#include<exception>
#include<stdexcept>
using namespace std;
class ThreadHandler
{
public:
int createThread(void (*function)(void*),void* input);
void setThreadID(int);
int getThreadID();
void runThread();
/* Constructor for ThreadHandler*/
ThreadHandler();
virtual ~ThreadHandler();
protected:
private:
int mThreadID;
pthread_t thread;
};
/* Function: ThreadHandler() */
ThreadHandler::ThreadHandler():mThreadID(0)
{
cout<<"\n ThreadHandling - constructor";
}
/* Function: ~ThreadHandler() */
ThreadHandler::~ThreadHandler()
{
}
/*Function: setThreadID() - set mThreadID value after
thread creation*/
void ThreadHandler::setThreadID(int thread_id)
{
cout<<"\n setThreadID function Entry";
mThreadID=thread_id;
cout<<"\n Thread ID: "<<mThreadID;
cout<<"\n setThreadID function Exit";
}
/*Function: getThreadID() - return a thread ID after
thread creation*/
int ThreadHandler::getThreadID()
{
return mThreadID;
}
/*Function: createThread() - Create Thread
and Assign function dynamically */
int ThreadHandler::createThread(void (*callingFunction)(void*),void* input)
{
cout<<"\n createThread Function Entry";
int thread_id=pthread_create(&thread,(pthread_attr_t*)callingFunction,NULL,input);
if(thread_id)
{
cout<<"\n Failed to create the thread and throw an exception";
throw;
}
setThreadID(thread_id);
cout<<"\n createThread Function Exit";
return thread_id;
}
/* Function: runThread() -- Joinable thread for exection*/
void ThreadHandler::runThread()
{
cout<<"\n Join the thread for runnable"<<endl;
pthread_join(this->thread,NULL);
}
/*Function to execute by the thread*/
void ThreadFunction(void* input)
{
cout<<"\n Thread Execution: "<<input;
}
/*Main part of the Class and Execution*/
int main()
{
char* msgPtr="I am running";
ThreadHandler *objThread = new ThreadHandler();
if(objThread==NULL)
{
cout<<"\n Failed to create a ThreadHandler object";
return -1;
}
/*Create a function pointer to pass*/
//void* (*FunctionPtr)(void*)=NULL;
//FunctionPtr = &ThreadFunction;
try
{
cout<<"\n -- start create a thread --";
objThread->createThread(&ThreadFunction,reinterpret_cast<void*>(msgPtr));
}
catch(exception& e)
{
cout<<"\n Exception while creating the thread";
}
return 0;
}
错误: ThreadHandling - 构造函数 - 开始创建一个帖子 -
编程接收信号SIGSEGV,分段故障。 allocate_stack中的0x00007ffff76aab8c(stack =,pdp =,attr = 0x400ead) 在allocatestack.c:415 415 allocatestack.c:没有这样的文件或目录。
答案 0 :(得分:1)
<强>问题强>
您似乎正在以错误的顺序将参数传递给pthread_create
。
来自man-pages:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
<强>解决方案强>
改变这个:
pthread_create(&thread,(pthread_attr_t*)callingFunction,NULL,input);
到此:
pthread_create(&thread, NULL, callingFunction, input);
<强>建议强>
我建议使用std::thread,因为这样可以更轻松地处理线程,尤其是在与std::function结合使用时。