February 2020
Intermediate to advanced
292 pages
8h 54m
English
In this recipe, we'll create a multi-threaded program to increment an integer until it reaches 200000. Again, the code section that takes care of the increments must be protected and we'll use POSIX semaphores. The main method will create the two threads and ensure that the resources are destroyed correctly. Let's get started:
#include <pthread.h>#include <semaphore.h>#include <iostream>struct ThreadInfo{ sem_t sem; int counter;};void* increment(void *arg){ ThreadInfo* info = static_cast<ThreadInfo*>(arg); sem_wait(&info->sem); std::cout << "Thread Started ... " << std::endl; for (int i = 0; i < 100000; ++i) info->counter++; ...Read now
Unlock full access