I was searching long before ask this question, and I can't find how to solve my problem. I have five threads(Workers), this workers are mining gold,transport gold to avant poste and unload it there.
And my problem is there that when the worker is mining gold, user can input b to check is there enough gold, and if this is true to build barrack.
When worker is mining gold there is 2 sec sleep that is why I use pthread_cond_timedwait()
.
I have global variables which are storing barracks number, gold on map and gold in avant poste
Here is the pseudo code.
void makeBarrack(size_t data) {
timespec waitTime = { 2, 0 };
pthread_mutex_lock(&check_mutex);
while (wantBarrack) {
pthread_cond_timedwait(&condp, &gold_mutex, &waitTime);
}
std::cout << "Worker" << data << "is making barrack" << std::endl;
wantBarrack = false;
pthread_mutex_lock(&unload_mutex);
avantPost -= 100;
pthread_mutex_unlock(&unload_mutex);
barracks++;
pthread_mutex_unlock(&check_mutex);
}
void *work(void *data, char input) {
size_t thread_num = (size_t) data;
pthread_mutex_lock(&gold_mutex);
timespec waitTime = { 2, 0 };
if ((input == 'B' || input == 'b') && avantPost >= 100) {
wantBarrack = true;
input = 0;
} else if ((input == 'B' || input == 'b') && avantPoste < 100) {
std::cout << "There is " << avantPoste << " gold" << std::endl;
}
while (wantBarrack) {
pthread_cond_timedwait(&condp, &gold_mutex, &waitTime);
}
makeBarrack(data);
}
I an trying to make something like consumer producer but in my task I need to do something(mine gold) instead of waiting other threads to mine.
Other question is do I need to use same mutex in this two functions?
P.S. I am novice in multithreading and it will be good someone to edit my question if there is something wrong.
The problem was threre that I've learnt that I can use cv in simple if.The main reason to use cv is thath we can block our thread without blocking other threads (It's unlocking the mutex while waiting on cv).And we just need to signal thath the conditition is done and we are ready to unblock(release) the thread and make the function we want. I am using pthread_cond_timedwait()
because I can block my thread for time I want.