Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we write -D_REENTRANT while compiling C code using threads

Tags:

gcc

We write this statement when we are compiling a C program that has threads implemented in them. I could not understand why we use -D_REENTRANT here. e.g gcc t1.c -lpthread -D_REENTRANT

like image 977
Ahmed Avatar asked Dec 19 '13 04:12

Ahmed


People also ask

Why do we use threads in C?

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. C does not contain any built-in support for multithreaded applications.

Why do we need threads in programming?

Threads are very useful in modern programming whenever a process has multiple tasks to perform independently of the others. This is particularly true when one of the tasks may block, and it is desired to allow the other tasks to proceed without blocking.

Why do we use multiple threads?

What Is Multithreading Used For? The main reason for incorporating threads into an application is to improve its performance. Performance can be expressed in multiple ways: A web server will utilize multiple threads to simultaneous process requests for data at the same time.


1 Answers

Actually, the recommended way to compile with threads in GCC is using the -pthread option. It is equivalent to -lpthread -D_REENTRANT so you have actually no problem.

The flags do the following:

  • -lpthread instructs the linker to use the appropriate library versions for thread compatibility.

  • -D_REENTRANT tells the compiler to use the declarations (functions, types, ...) necessary for thread usage.

like image 95
rodrigo Avatar answered Nov 18 '22 01:11

rodrigo