Advertisement

Segmentation fault with pthreads

Started by December 09, 2003 10:22 AM
9 comments, last by Evil Steve 20 years, 10 months ago
Hi, i''m having a bit of trouble with pthreads. The following code causes a segmentation fault on the line pthread_create

void* Proc(void* pParam)
{
   printf("In thread...\n");
   return NULL;
}

int main(int argc, char** argv)
{
pthread_t id;
   
   printf("Starting...\n");
   pthread_create(&id,NULL,Proc,NULL);
   printf("Started...\n");
   usleep(1000000);
   return 0;
}
Output:

[steve@server test]# ./test
Starting...
Segmentation fault
[steve@server test]#
Anyone know whats causing this problem? I thought it might be that the attr variable can;t be NULL, but all the docs i''ve found say it can be NULL to use the default values, and i can''t find any useful information about initializing the structure. Cheers, Steve
Hmm... I''m pretty sure you''re supposed to initialize a
pthread_attr structure, like this:

pthread_attr_t attr;pthread_attr_init(&attr);pthread_create(&threadID, &attr, my_thread_func, NULL);pthread_attr_destroy(&attr);




Kami no Itte ga ore ni zettai naru!
神はサイコロを振らない!
Advertisement
You code works just fine for me.

It also works for me. What happens if you run it with gdb?

The official zorx website
Zorx (a Puzzle Bobble clone)Discontinuity (an animation system for POV-Ray)
Hmm... compiling this:
#include <pthread.h>#include <stdio.h>#include <unistd.h>void* Proc(void* pParam){   printf("In thread...\n");   return NULL;}int main(int argc, char** argv){pthread_t id;      printf("Starting...\n");   pthread_create(&id,NULL,Proc,NULL);   printf("Started...\n");   usleep(1000000);   return 0;}

Gives:
[root@server steve]# g++ Main.o -o testMain.o(.text+0x4c): In function `main':: undefined reference to `pthread_create'collect2: ld returned 1 exit status[root@server steve]#  


Which i didn't get before...

Sorry i didn't reply earlier, my smtp server seems to be borked...

Edit: Is there a library i need to link to? (and if so, how do i link with g++? [I'm a g++ newbie...])


[edited by - Evil Steve on December 11, 2003 6:37:51 PM]
Yes, you need to link to the pthread library (at the command line, it''d be done with -lpthread). I had put the headers in myself when I was lazily-checking-via-compiler your code.


Advertisement
You should compile with -lpthread option.
I agree with tangentz, you should be using pthread_attr_init()
edit: damn, I'm slow...
SwSh website!

[edited by - SwSh on December 11, 2003 6:51:33 PM]
[root@server steve]# g++ test.o -lpthreads -o test/usr/bin/ld: cannot find -lpthreadscollect2: ld returned 1 exit status[root@server steve]# 

Is that right?

I''ve changed the code to initialize attr too.
-lpthread, not -lpthreads

"Sneftel is correct, if rather vulgar." --Flarelocke
Ah ha, it compiles and runs fine now. Ok, lets try compiling the real app...

This topic is closed to new replies.

Advertisement