Threads usage in C programming

Threads usage in C programming

If you want to write tables from two – five at the same time and using pencils and papers we need at least four writing hands ( four people), four pencils and four papers one for each to write a table. This method is called parallelism. In this method, we obtain the result in a short time. If one person does the same task it takes four times longer. (To understand threads)

In computer C programming, this process is called threads. By using these we get efficiency in programs to solve complex issues. In the Linux environment, POSIX threads have appeared. These are called pthreads and having a library named pthread.

Types of threads:

These are generally two types.

1. Joinable threads
2. Detachable threads

Joinable threads need to join them, whereas Detachable threads run their self. In every program main function, itself is the main thread.

To create pthread in C program we using phtread_create() function. In this function, it takes four arguments.

1. thread id
2. attribute
3. function to call
4. only argument to calling function

Example 1:

Here is an example C program to demonstrate joinable.

To compile below program
gcc thread.c -o thread -lpthread

To execute the program
./thread

The result is almost like this:

result of thread.c

result of thread.c For more information on the pthread_create function refer the below link

https://linux.die.net/man/3/pthread_create

Example 2:

Here is another program to demonstrate the detachable type.

To compile below program
gcc thread_detach.c -o thread_detach -lpthread

To execute the program
./thread_detach

The result is almost like this:

thread_detach.c

For more information on the pthread_detach function refer the below link:

https://linux.die.net/man/3/pthread_detach

 

Leave a Reply

Your email address will not be published. Required fields are marked *