Basics of multithreading in C (2024)

Basics of multithreading in C (1)

Nathanael Demacon

Posted on • Updated on

Basics of multithreading in C (3) Basics of multithreading in C (4) Basics of multithreading in C (5) Basics of multithreading in C (6) Basics of multithreading in C (7)

#programming #c #threading #multithreading

C is a language that runs on one thread by default, which means that the code will only run one instruction at a time. In some cases you'll need to do multiple instructions at a time, a graphical interface for instance, will not stop when it performs an action related to a button's click. That's what we call multithreading, not to be confused with asynchronous operations that can be performed in only one thread that does multiple tasks.

A thread is a task that runs linked to a process. A process we can have multiple threads and threads can run other threads and so on.

By default a process runs on a single thread. Each thread is new tasks that can be run indefinitely and in parallel to the other threads.

Like said in the title, this post will talk about multithreading in C, so we will do C!

On POSIX operating systems, there is a library named pthread.h, which does exactly what it says, create threads! To use it under compilers, you'll need to link it with -lpthread argument (ex: gcc -lpthread main.c).

#include <pthread.h>#include <unistd.h>#include <stdio.h>voidwait(void){ sleep(2); printf("Done.\n");}intmain(void){ pthread_t thread; int err; err = pthread_create(&thread, NULL, wait, NULL); if (err) { printf("An error occured: %d", err); return 1; } printf("Waiting for the thread to end...\n"); pthread_join(thread, NULL); printf("Thread ended.\n"); return 0;}

The output will be:

Waiting for the thread to end...Done. (~2 seconds after)Thread ended.

The main thread continued and printed a message while the created thread was operating and it's only one line to call a function in a new thread, pretty easy for C uh? Maybe you're a little lost, I will explain the code.

First of all, we include the pthread.h library, like said above, it contains all the functions needed to perform multithreading tasks. Then we include unistd.h which is containing the sleep() function. And then the stdio.h for printf().

pthread_create function is called to create the thread. It requires a pthread_t, which is the thread descriptor, a pointer to a void function and some other parameters that I will not describe here, the function's arguments for instance.

pthread_join is used to link the current thread process to another thread. It literally makes the program stops in order to wait for the end of the selected thread.

Doing multiple operations on one target at the same time is very dangerous, the best example I can give is for databases. If three threads want to write a single file at the same time, it would be a problem because an hard drive can't go as fast as a CPU does. In this case we should lock the other threads in order to not overload the hard drive with tasks that can corrupt the file. Mutex can be used to lock the other threads.

In practice, we use mutex to tell if the task is locked or unlocked.

#include <pthread.h>#include <unistd.h>#include <stdio.h>pthread_mutex_t lock;int j;voiddo_process(){ pthread_mutex_lock(&lock); int i = 0; j++; while(i < 5) { printf("%d", j); sleep(1); i++; } printf("...Done\n"); pthread_mutex_unlock(&lock);}intmain(void){ int err; pthread_t t1, t2; if (pthread_mutex_init(&lock, NULL) != 0) { printf("Mutex initialization failed.\n"); return 1; } j = 0; pthread_create(&t1, NULL, do_process, NULL); pthread_create(&t2, NULL, do_process, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); return 0;}

The output will be:

111111...Done222222...Done

So, as you can see, the thread t2 was done totally after t1, so the mutex worked! It's not the result of the pthread_join calls as they only change something for the current thread (here the main thread), you can try to join t2 before t1, it will perform the same thing.

Pretty much the same thing as the mutex, the semaphores are used to be controlled by any thread. The notion of ownership is not present in the case of a semaphore, so they can be locked and unlocked by any part of the program.

That was pretty easy don't you think? C functions are very powerful to perform such actions, a great power carries a great responsibility.

Basics of multithreading in C (8)

Top comments (17)

Subscribe

edA‑qa mort‑ora‑y

edA‑qa mort‑ora‑y

I'm a creative programmer and puzzles designer.I cook monsters.

  • Email

    eda-qa@disemia.com

  • Education

    Lots

  • Work

    Programmer, Writer, Speaker, Puzzle Designer at Edaqa's Room

  • Joined

Jan 9 '19

  • Copy link

pthread is outdated since availability of C11 which introduced standard threading in C. The header files is <threads.h> with functions like thrd_create.

The standard functions for threading, conditions, and signalling, provide guarantees that pthreads cannot.

Nathanael Demacon

Nathanael Demacon

  • Location

    France

  • Education

    ESGI

  • Joined

Jan 10 '19

  • Copy link

I have my answers, threads.h is better to use even if it's not POSIX (stackoverflow.com/a/9377007)

Nathanael Demacon

Nathanael Demacon

Jan 10 '19

  • Copy link

pthread.h is POSIX compliant, threads.h isn't.

But sure you can use it, it's implemented in linux and freeBSD kernels.

Noah11012

Noah11012

  • Joined

Jan 10 '19

  • Copy link

But threads.h is C11 compliant so by now ALL compilers have support for C11 at least for the three major ones:

MSVC
GCC
CLANG

Nathanael Demacon

Nathanael Demacon

  • Location

    France

  • Education

    ESGI

  • Joined

Jan 10 '19

  • Copy link

Yup, seems nice, their is just a lack of documentation, I wanted to know what did it really does.

Noah11012

Noah11012

  • Joined

Jan 10 '19

  • Copy link

You can find documentation here: en.cppreference.com/w/c/thread

JL2210

JL2210

  • Joined

Jan 22 '20

  • Copy link

Well, it's the C libraries for two of those platforms that are supposed to implement threads.h (even though I'm pretty sure glibc doesn't), although I'm not sure what Windows does.

JL2210

JL2210

  • Joined

Jan 22 '20

  • Copy link

It's not the kernels, it's the C libraries. You can have a kernel installed and not be able to do anything without a C library.

Phil Ashby

Phil Ashby

30+ years of tech, retired from an identity intelligence company, now part-time with an insurance broker.Dev community mod - mostly light gardening & weeding out spam :)

  • Location

    Felixstowe, UK

  • Education

    M.Eng (hons) Electronics, MIET, MBCS, AMCIISec, CEH

  • Pronouns

    he/him

  • Work

    Willis Towers Watson (aka WTW) part-time.

  • Joined

Jan 9 '19

  • Copy link

Thanks Nathanael! Nice starter article on pthreads :)

For the curious, Lawrence Livermore National Laboratory have this article with more background and examples of why you might use the various features available in pthreads: computing.llnl.gov/tutorials/pthre...

It's also a good idea to make sure you are using thread-safe library functions, here's a nice SO question and answer: stackoverflow.com/questions/125957...

Enjoy your full control of the CPU!

Nathanael Demacon

Nathanael Demacon

  • Location

    France

  • Education

    ESGI

  • Joined

Jan 9 '19

  • Copy link

Glab that you enjoyed it!

I'm starting to understand a lot about pure Computer Science since I got some courses about the theory of operating systems. It's so fascinating to learn how things really works beyond the compilers and why things are like that in programming languages!

Akshay Hiremath

Akshay Hiremath

  • Joined

Nov 21 '19

  • Copy link

Can you suggest that courses pls.

Nathanael Demacon

Nathanael Demacon

  • Location

    France

  • Education

    ESGI

  • Joined

Nov 21 '19

  • Copy link

For the theory of operating systems, I see this subject at my school (engineering school), but for programming languages I heard that Engineering a Compiler is very great when starting in this domain.

The Dragon Book is very good but much more advanced.

Ondrej

Ondrej

Philosophy, maths & human rights focused technology

  • Location

    .onion

  • Joined

Jan 9 '19

  • Copy link

Thank god for every C-related article here (for us, who have interest in low-level programming). Thanks, Nathanael!

Nathanael Demacon

Nathanael Demacon

  • Location

    France

  • Education

    ESGI

  • Joined

Jan 9 '19

  • Copy link

C can be a very scary language at first but it's so captivating, I'm happy that you enjoyed reading this article 😄

Shreyos Ghosh

Shreyos Ghosh

A newbie into computer science...

  • Education

    JIS University

  • Pronouns

    He/Him

  • Joined

Mar 6 '23 • Edited on Mar 8 • Edited

  • Copy link

Hey, recently I worked with the C++ standard thread library and made a series about it, where I've talked about the mutexes and locks. I hope you'll find it useful. dev.to/shreyosghosh/series/20850

JL2210

JL2210

  • Joined

Jan 22 '20

  • Copy link

Why can't you use a for loop? for( i = 0; i < 5; i++ )

Nathanael Demacon

Nathanael Demacon

  • Location

    France

  • Education

    ESGI

  • Joined

Jan 22 '20

  • Copy link

You can and should do a for loop. It's been 1 year since I did this article, I think it's time to rewrite it with my current knowledge :)

View full discussion (17 comments)

For further actions, you may consider blocking this person and/or reporting abuse

Basics of multithreading in C (2024)

FAQs

What is multithreading in C for beginners? ›

In C, the term "multithreading" describes the use of numerous threads concurrently. Each thread does a different task. Due to the concurrent nature of multithreading, many tasks may be carried out at once.

What is the basics of multithreading? ›

Multithreading is a programming concept in which the application can create a small unit of tasks to execute in parallel. If you are working on a computer, it runs multiple applications and allocates processing power to them. A simple program runs in sequence and the code statements execute one by one.

Is C good for multithreading? ›

Can we write multithreading programs in C? Unlike Java, multithreading is not supported by the language standard. POSIX Threads (or Pthreads) is a POSIX standard for threads.

What are the concepts of threads in C? ›

Thread functions in C/C++
  • thread: pointer to an unsigned integer value that returns the thread id of the thread created.
  • attr: pointer to a structure that is used to define thread attributes like detached state, scheduling policy, stack address, etc. ...
  • start_routine: pointer to a subroutine that is executed by the thread.
May 9, 2023

How to write a multithreading program in C? ›

C Program to illustrate the use of pthread basic functions

In the main() function, we create a variable called thread_id, which is of type pthread_t—an integer used to identify the thread. After declaring thread_id, we use the pthread_create() function to make a new thread.

What is multithreading in C? ›

Multithreading in C refers to the use of many threads inside a single process. Each thread serves a separate function. Multithreading operates concurrently which means numerous jobs may be executed simultaneously. Multithreading also minimizes the consumption of resources of the CPU.

How do you explain multithreading to a child? ›

It is like when several actions are done in a parallel manner on the same object. Two repairmen are working on the same car. If one changes the front tires, the other the rear ones, it is okay. But if they are both grabbing for the same tire at the same time, then there is a problem.

What is multithreading with example? ›

What is MultiThreading? Multithreading enables us to run multiple threads concurrently. For example in a web browser, we can have one thread which handles the user interface, and in parallel we can have another thread which fetches the data to be displayed. So multithreading improves the responsiveness of a system.

Why use threads in C? ›

Threads are a means to identify and utilize potential parallelism in a program. You can use them in your program design both to enhance its performance and to efficiently structure programs that do more than one thing at a time.

When to use threads in C? ›

If you only have access to the program executable to compute information, you will definitely have to use processes. We use threads when it doesn't matter the concurrency between threads and processes are use so the OS can give different tasks to different cores and they happen to execute in parallel independently.

Which language is best for multithreading? ›

When architecting a new application, it's important to choose the right language for the job at hand. If you need great multithreaded support, then you should choose a language like Java or C++. If you need good performance, then you should consider using Python or Go.

How to identify threads in C? ›

pthread_self() in C

This function can uniquely identify the existing threads. But if there are multiple threads, and one thread is completed, then that id can be reused.

What is concurrency in C? ›

Concurrency refers to the ability of a program to execute multiple tasks simultaneously. In the context of C++, concurrency allows you to perform multiple operations concurrently, making efficient use of modern multi-core processors.

What is the difference between a thread and a process in C? ›

Computer processes are independent program instances with their own memory space and resources, operating in isolation. In contrast, threads are smaller units within processes that share the same memory, making communication easier but requiring careful synchronization.

What is multithreading explain with example? ›

What is MultiThreading? Multithreading enables us to run multiple threads concurrently. For example in a web browser, we can have one thread which handles the user interface, and in parallel we can have another thread which fetches the data to be displayed. So multithreading improves the responsiveness of a system.

What is meant by multithreading in programming? ›

Multithreading is a model of program execution that allows for multiple threads to be created within a process, executing independently but concurrently sharing process resources. Depending on the hardware, threads can run fully parallel if they are distributed to their own CPU core.

Top Articles
Latest Posts
Article information

Author: Gregorio Kreiger

Last Updated:

Views: 6743

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Gregorio Kreiger

Birthday: 1994-12-18

Address: 89212 Tracey Ramp, Sunside, MT 08453-0951

Phone: +9014805370218

Job: Customer Designer

Hobby: Mountain biking, Orienteering, Hiking, Sewing, Backpacking, Mushroom hunting, Backpacking

Introduction: My name is Gregorio Kreiger, I am a tender, brainy, enthusiastic, combative, agreeable, gentle, gentle person who loves writing and wants to share my knowledge and understanding with you.