Book Image

Practical C Programming

By : B. M. Harwani
Book Image

Practical C Programming

By: B. M. Harwani

Overview of this book

Used in everything from microcontrollers to operating systems, C is a popular programming language among developers because of its flexibility and versatility. This book helps you get hands-on with various tasks, covering the fundamental as well as complex C programming concepts that are essential for making real-life applications. You’ll start with recipes for arrays, strings, user-defined functions, and pre-processing directives. Once you’re familiar with the basic features, you’ll gradually move on to learning pointers, file handling, concurrency, networking, and inter-process communication (IPC). The book then illustrates how to carry out searching and arrange data using different sorting techniques, before demonstrating the implementation of data structures such as stacks and queues. Later, you’ll learn interesting programming features such as using graphics for drawing and animation, and the application of general-purpose utilities. Finally, the book will take you through advanced concepts such as low-level programming, embedded software, IoT, and security in coding, as well as techniques for improving code performance. By the end of this book, you'll have a clear understanding of C programming, and have the skills you need to develop robust apps.
Table of Contents (20 chapters)

Using mutex to share data between two threads

Running two or more threads independently, where each accesses its own resources, is quite convenient. However, sometimes, we want the threads to share and process the same resource simultaneously so that we can finish a task faster. Sharing a common resource may lead to problems, as one thread might read the data before the other thread writes the updated data, leading to an ambiguous situation. To avoid such a situation, mutex is used. In this recipe, you will learn how to share common resources between two threads.

How to do it…

  1. Define two variables of the pthread_t type to store two thread identifiers. Also, define a mutex object:
pthread_t tid1,tid2;
pthread_mutex_t...