views:

4069

answers:

6

I have used fork() in C to start another process. How do I start a new thread?

+1  A: 

pthreads is a good start, look here

epatel
A: 

Check out the pthread (POSIX thread) library.

Jay Conrod
+4  A: 

It depends on the platform. Here's how to do it on Windows:

http://msdn.microsoft.com/en-us/library/ms682453.aspx

Eric Z Beard
As explained in the CreateThread documentation you linked to, if the program uses the C runtime library, _beginthreadex should be used, not CreateThread.
ChrisN
Thanks, I hadn't noticed that. How do you know if you're using the CRT? I thought everything used it.
Eric Z Beard
@Eric: You can tell the compiler to not include the default libraries. Then you cannot use the CRT by accident and you can use the Win32 functions entirely.
Zan Lynx
+14  A: 

Since you mentioned fork() I assume you're on a Unix-like system, in which case POSIX threads (usually referred to as pthreads) are what you want to use.

Specifically, pthread_create() is the function you need to create a new thread. Its arguments are:

int  pthread_create(pthread_t  *  thread, pthread_attr_t * attr, void *
   (*start_routine)(void *), void * arg);

The first argument is the returned pointer to the thread id. The second argument is the thread arguments, which can be NULL unless you want to start the thread with a specific priority. The third argument is the function executed by the thread. The fourth argument is the single argument passed to the thread function when it is executed.

Commodore Jaeger
+7  A: 

AFAIK, ANSI C doesn't define threading, but there are various libraries available.

If you are running on Windows, link to msvcrt and use _beginthread or _beginthreadex.

If you are running on other platforms, check out the pthreads library (I'm sure there are others as well).

Brannon
+2  A: 

Threads are not part of the C standard, so the only way to use threads is to use some library (eg: POSIX threads in Unix/Linux, _beginthread/_beginthreadex if you want to use the C-runtime from that thread or just CreateThread Win32 API)

botismarius