Click to See Complete Forum and Search --> : PThreads in C++


astewix
04-18-2003, 06:51 AM
Hi Everyone,

Just wondering if someone could provide an example of spawning a few threads in C++ and just getting each thread to print something to the console. I've been searching around for some example code yet none of them work (it compiles fine but seg faults when pthread_create is called).

Am i supposed to compile it with some special flags or something? I am running gcc version 3.2.2 and it is configure with --enable-threads=posix.

Your help is appreciated.

bwkaz
04-18-2003, 10:07 AM
pthreads are a C library, not C++. Are you wrapping the <pthread.h> include with something like:

extern "C" {
#include <pthread.h>
}? Because I'm not sure, but I think you need to be. Also, are you passing a global function to pthread_create, or a member of a class? If you're passing a member of a class, then it has to be a static member due to the way the pthread_create function works under the hood (you might also be able to declare the function as non-static, and make it take no arguments, then pass the address of the relevant object to pthread_create as the void *arg parameter, but I don't know for sure if that'll work).

astewix
04-18-2003, 10:51 AM
thanks for that. It wasn't the problem though.

I just had to compile it with the -lpthreads flag and it was fine.

bwkaz
04-18-2003, 01:06 PM
You didn't get link errors without -lpthread?

That's ... ummm, odd. Well, whatever works, I guess. ;)