Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print numbers in sequence using thread synchronization
Thread synchronization allows multiple threads to coordinate and execute in a specific order. In this example, we create n threads where each thread prints its number in sequence − thread 1 prints 1, thread 2 prints 2, and so on. We use mutex locks and condition variables to ensure proper synchronization.
Note: To compile and run this program, you need to link with the pthread library:
gcc program.c -lpthread -o program
Syntax
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_variable; pthread_mutex_lock(&mutex); pthread_cond_wait(&condition_variable, &mutex); pthread_cond_signal(&condition_variable); pthread_mutex_unlock(&mutex);
Example: Sequential Number Printing with Threads
This program demonstrates thread synchronization using mutex and condition variables to print numbers in sequence −
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t* cond = NULL;
int threads;
volatile int count = 0;
volatile int iterations = 0;
void* sync_thread(void* num) {
int thread_number = *(int*)num;
while (iterations < 20) { // Limit iterations for demo
pthread_mutex_lock(&mutex);
// Wait until it's this thread's turn
while (thread_number != count && iterations < 20) {
pthread_cond_wait(&cond[thread_number], &mutex);
}
if (iterations < 20) {
printf("%d ", thread_number + 1);
fflush(stdout);
count = (count + 1) % threads;
iterations++;
// Signal the next thread
pthread_cond_signal(&cond[count]);
}
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t* thread_id;
int i;
int* thread_arr;
threads = 5; // Fixed number for demo
printf("Creating %d threads for sequential printing:<br>", threads);
// Allocate memory for condition variables, thread IDs and thread array
cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t) * threads);
thread_id = (pthread_t*)malloc(sizeof(pthread_t) * threads);
thread_arr = (int*)malloc(sizeof(int) * threads);
// Initialize condition variables
for (i = 0; i < threads; i++) {
pthread_cond_init(&cond[i], NULL);
}
// Create threads
for (i = 0; i < threads; i++) {
thread_arr[i] = i;
pthread_create(&thread_id[i], NULL, sync_thread, (void*)&thread_arr[i]);
}
// Wait for all threads to complete
for (i = 0; i < threads; i++) {
pthread_join(thread_id[i], NULL);
}
printf("\nAll threads completed.<br>");
// Cleanup
for (i = 0; i < threads; i++) {
pthread_cond_destroy(&cond[i]);
}
free(cond);
free(thread_id);
free(thread_arr);
pthread_mutex_destroy(&mutex);
return 0;
}
Creating 5 threads for sequential printing: 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 All threads completed.
How It Works
- Mutex Lock: Ensures only one thread can access the critical section at a time
- Condition Variables: Allow threads to wait for their turn and signal the next thread
-
Sequential Control: The
countvariable tracks which thread should execute next -
Thread Synchronization: Each thread waits until
countmatches its thread number
Key Points
- Always initialize condition variables with
pthread_cond_init() - Use
pthread_cond_wait()to make threads wait for their turn - Use
pthread_cond_signal()to wake up the next thread in sequence - Remember to destroy condition variables and free allocated memory
Conclusion
Thread synchronization using mutex and condition variables ensures threads execute in a specific order. This technique is essential for coordinated multi-threaded programming where sequence matters.
Advertisements
