I'm using the method 'pthread_create' in my program, and get a segmentation fault INSIDE THIS METHOD.
What can possibly cause this? I'm calling this function with the correct arguments' types!
this is the code:
pthread_t* _daemon;
void* writer(void* arg){
// stuff that dont involve "arg"...
}
int initdevice(){
if(pthread_create(_daemon, NULL, &writer, NULL) != 0) //seg in this line
{
cerr << "system error\n";
return ERR_CODE;
}
return SUCCESS;
}
int main () {
initdevice();
return 0;
}
Note: I've tried to run it also without the '&' before the calling to writer in pthread_create, and also - we've tried sending to this method some void* argument instead of the last NULL argument.
DESCRIPTION. The pthread_create() function is used to create a new thread, with attributes specified by attr, within a process. If attr is NULL, the default attributes are used. If the attributes specified by attr are modified later, the thread's attributes are not affected.
pthread_create() returns zero when the call completes successfully. Any other return value indicates that an error occurred.
On success, pthread_create() returns 0; on error, it returns an error number, and the contents of *thread are undefined.
The maximum number of threads is dependent upon the size of the private area below 16M. pthread_create() inspects this address space before creating a new thread. A realistic limit is 200 to 400 threads.
Your probelem is here:
pthread_t* _daemon;
This should be:
pthread_t daemon;
Then change the call to pthread_create:
if(pthread_create(&daemon, NULL, &writer, NULL) != 0)
The idea is that pthread_create takes a pointer to an existing pthread_t object so that it can fill in the details. You can think of it as the C version of a constructor. Initially the pthread_t object is uninitialized this initializes it.
In addition your code is still probably not going to always work as you do not wait for the thread to finish. Make sure your main thread does not finish before all the children:
int main ()
{
initdevice();
pthread_join(daemon, NULL); // wait for the thread to exit first.
return 0;
}
you must allocate _daemon
variable
with new
or malloc
function, because you have use of a pointer
. like bellow :
pthread_t* _daemon;
_daemon = new pthread_t;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With