I am implementing a producer consumer with c++ using clone2() and semaphores but it has an unexpected behavior.
Here is the code:
#include <iostream>
#include <semaphore.h>
#include <unistd.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sched.h>
#include <errno.h>
#include <mutex>
#include <sys/wait.h>
using namespace std;
sem_t empty, full;
mutex mutexSem;
int var = 1;
int items[10];
int in = 0;
int out = 0;
static int produce(void * arg) {
while (true) {
sem_wait(&empty);
mutexSem.lock();
cout << "produce position: " << in << endl;
items[in] = var++;
in = (in+1) % 10;
mutexSem.unlock();
sem_post(&full);
}
}
static int consume(void *arg) {
while (true) {
sem_wait(&full);
mutexSem.lock();
cout << "consume position: " << out << endl;
items[out] = 0;
out = (out + 1 ) % 10;
mutexSem.unlock();
sem_post(&empty);
}
}
int
main(int argc, char *argv[]) {
int emptyResponse = sem_init(&empty, 0, 10);
int fullResponse = sem_init(&full, 0, 0);
void ** child_stack;
child_stack = (void **) malloc(16384) + 16384 / sizeof(*child_stack);
if (errno != 0 || emptyResponse != 0
|| fullResponse != 0) {
cout << "errNo->" << errno << endl;
}
clone(produce, child_stack, CLONE_VM | CLONE_FILES , NULL);
sleep(4);
clone(consume, child_stack, CLONE_VM | CLONE_FILES, NULL);
return 0;
}
I compile the code like
g++ -std=c++11 clone2.cpp -o clone2 -lpthread
And each time i run the code it produces a different result. I want to produce an infinite producer/consumer that each time an item is produced, then i will be consumed. I don't know why after producing 10 items, then it consumes 10 items and the process finish. I don't know also why i have to use a sleep(anyNumber) between the two threads, even though it won't do anything. Someone can tell me pleae if the FLAGS that i am setting are ok, and how this clone work.
This is an example of an output:
produce: 0
produce: 1
produce: 2
produce: 3
produce: 4
produce: 5
produce: 6
produce: 7
produce: 8
produce: 9
consume: 0
consume: 1
consume: 2
consume: 3
consume: 1515067019
consume: 5
consume: 6
consume: 7
consume: 8
consume: 9
Sometimes is like it, sometimes it has a segmentation fault, sometimes it just don't print any number so it will appear like
consume:
consume: 5
And so on...
NOTE: It's MANDATORY to use clone2() and i am using ubuntu 14.04 LTS , Intel core i7 64 bits
Thanks!