vendredi 30 janvier 2015

Semaphore not working C++

I am new to semaphore and trying to write a very basic example to get to learn it better. My code has three arrays:



b1[5]={1;2;3;4;5}
b2[5]={6;7;8;9;10}
x[10]


I have a function that takes b1 or b2 and update x to have it as follow:



x={0;1;2;3;4;5;6;7;8;9}


My code is the following:



#include <sys/types.h> /* Primitive System Data Types */
#include <errno.h> /* Errors */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include <thread> /* C++11 Threads */
#include <string.h> /* String handling */
#include <semaphore.h> /* Semaphore */
#include <Windows.h> /* windows */
using namespace std;

/* prototype for thread routine */
void handler(int x[], int b[], int start, int id);

/* global vars */
sem_t mutex;
vector<std::thread> threadList;

int main()
{
int i[2];
int x[10];
int b1[5];
int b2[5];
sem_init(&mutex, 0, 1); /* initialize mutex to 1 - binary semaphore */
/* second param = 0 - semaphore is local */
i[0] = 0;
i[1] = 1;

// Update the matrix
for (int j = 0; j < 5; j++)
{
b1[j] = j;
b2[j] = j+5;
}



threadList.push_back(std::thread(handler, x, b1, 0, 0));
threadList.push_back(std::thread(handler, x, b2, 5, 1));

// wait for all threads to finish
for (auto& threadID : threadList){
threadID.join();
}

sem_destroy(&mutex); /* destroy semaphore */

/* exit */
return 0;
} /* main() */

void handler(int x[], int b[], int start, int id)
{

for (int j = start; j < 5; j++)
{
x[j] = b[j];
}
printf("Thread %d: Waiting to print results...\n", id);
sem_wait(&mutex); /* down semaphore */
/* START CRITICAL REGION */
for (int j = start; j < 5; j++)
{
printf("x[%d] = %d\n", j , x[j]);
}
/* END CRITICAL REGION */
sem_post(&mutex); /* up semaphore */
}


The output of the code is the following:



Thread 0: Waiting to print results...
x[0] = 0
x[1] = 1
x[2] = 2
x[3] = 3
x[4] = 4
Thread 1: Waiting to print results...


However, I was expecting something as following



Thread 0: Waiting to print results...
x[0] = 0
x[1] = 1
x[2] = 2
x[3] = 3
x[4] = 4
Thread 1: Waiting to print results...
x[5] = 5
x[6] = 6
x[7] = 7
x[8] = 8
x[9] = 9


Any idea why the second thread does not enter the printing section of the code ?


Aucun commentaire:

Enregistrer un commentaire