What are processes and threads?

Whenever we run a program, the moment that it is loaded from the hard disk (or any other storage) into the memory, it becomes a process. A process is executed by a processor, and for its execution, it requires a program counter (PC) to keep track of the next instruction to be executed, the CPU registers, the signals, and so on.

A thread refers to a set of instructions within a program that can be executed independently. A thread has its own PC and set of registers, among other things. In that way, a process is comprised of several threads. Two or more threads can share their code, data, and other resources, but special care must be taken when sharing resources among threads, as it might lead to ambiguity and deadlock. An operating system also manages a thread pool. 

A thread pool contains a collection of threads that are waiting for tasks to be allocated to them for concurrent execution. Using threads from the thread pool instead of instantiating new threads helps to avoid the delay that is caused by creating and destroying new threads; hence, it increases the overall performance of the application.

Basically, threads enhance the efficiency of an application through parallelism, that is, by running two or more independent sets of code simultaneously. This is called multithreading.

Multithreading is not supported by C, so to implement it, POSIX threads (Pthreads) are used. GCC allows for the implementation of a pthread.

While using a pthread, a variable of the type pthread_t is defined to store the thread identifier. A thread identifier is a unique integer, that is ,assigned to a thread in the system.

You must be wondering which function is used for creating a thread. The pthread_create function is invoked to create a thread. The following four arguments are passed to the pthread_create function:

When two or more threads operate on the same data, that is, when they share the same resources, certain check measures must be applied so that only one thread is allowed to manipulate the shared resource at a time; other threads' access must be blocked. One of the methods that helps to avoid ambiguity when a resource is shared among threads is mutual exclusion.