Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I start threads in plain C?

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

like image 560
Hanno Fietz Avatar asked Sep 11 '08 15:09

Hanno Fietz


People also ask

How do you create a thread in C?

In main(), we declare a variable called thread_id, which is of type pthread_t, which is an integer used to identify the thread in the system. After declaring thread_id, we call pthread_create() function to create a thread. pthread_create() takes 4 arguments.

Can you use threads in C?

C does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C program using POSIX.

How do you start a STD thread?

std::thread is the thread class that represents a single thread in C++. To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object.


2 Answers

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.

like image 162
Commodore Jaeger Avatar answered Nov 06 '22 22:11

Commodore Jaeger


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).

like image 30
Brannon Avatar answered Nov 06 '22 20:11

Brannon