Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_create segmentation fault

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.

like image 944
Zach Avatar asked Apr 03 '11 16:04

Zach


People also ask

What is pthread_create in C?

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.

What is the return type of pthread_create?

pthread_create() returns zero when the call completes successfully. Any other return value indicates that an error occurred.

Which value does pthread_create () function return if it is successfully executed?

On success, pthread_create() returns 0; on error, it returns an error number, and the contents of *thread are undefined.

How many threads does pthread_create create?

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.


2 Answers

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;
}  
like image 152
Martin York Avatar answered Sep 30 '22 14:09

Martin York


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;