I am new to multithreading in c++.
What I want to do is to first create 2 threads. All threads will wait until they get a item to a set.I am using array of mutexes (For making threads to wait).After waiting they perform task(extract array). They will increase count to let main thread know that they extracted array. In this way after processing all three arrays I want my threads to print size of their extracted array and exit. But unfortunately my code is not getting terminated. I think it went into deadlock.
Can anyone please help.
This is my code:
#include <bits/stdc++.h>
#include<thread>
#include <chrono>
#include<mutex>
#include<condition_variable>
int n=5;
int count=0;
std::vector<std::vector<std::string>> sets;
std::vector<std::vector<std::string>> x;
std::mutex m[2],as,p;
std::condition_variable cv,cb;
int y=0,rt[2]={0};
int flag[2][3]={0};
int u=0;
void see(int i)
{
//cout<<"hii";
int j=0;
while(j<3)
{
std::unique_lock<std::mutex> lk(m[i]);
std::cout<<"\nwaiting\n"<<"i="<<i<<"set size="<<sets.size()<<"u="<<u<<" flag="<<flag[i][u]<<"\n";
cv.wait(lk, [i]{return (sets.size()>0&&flag[i][u]==0)?true:false;});
std::cout<<"came out i="<<i<<"\n";
flag[i][u]=1;
for(int qw=0;qw<4;qw++)
{
x[i].push_back(sets[0][qw]);
}
lk.unlock();
std::unique_lock<std::mutex> lq(as);
count++;
cb.notify_one();
lq.unlock();
j++;
}
std::cout<<"size of map of "<<i<<"is "<<x[i].size()<<"\n";
for(int w=0;w<12;w++)
{
std::cout<<x[i][w]<<" ";
}
std::cout<<"\n";
return;
}
int main()
{
std::vector<std::vector<std::string>> r;
for(int i=0;i<2;i++)
{
std::vector<std::string> e;
x.push_back(e);
}
std::vector<std::thread> threads;
std::string s[][4]={
{"Test","Create","Delete","Add"},
{"class","object","demo","status"},
{"Deep_Learning","Neural_Network","Blockchain"}
};
while(y<3)
{
std::vector<std::string> q;
for(int i=0;i<4;i++)
{
q.push_back(s[y][i]);
}
r.push_back(q);
y++;
}
for(int i=0;i<2;i++)
{
threads.push_back(std::thread(see,i));//creating thread
}
y=0;
//Main code starts from below
while(y<3)
{
std::cout<<"pushing\n";
sets.push_back(r[y]);//first passing set 1 to all threads
cv.notify_all();
std::unique_lock<std::mutex> lt(p);
cb.wait(lt, []{return count==2;});
std::cout<<"main y="<<y<<"\n";
sets.pop_back();
u++;
count=0;
y++;
}
for(int i=0;i<2;i++)
{
threads[i].join();
}
return 0;
}
Output:
waiting
i=0set size=pushing
waiting
i=1set size=0u=0 flag=0
came out i=1
waiting
i=1set size=1u=0 flag=1
0u=0 flag=0
came out i=0
waiting
i=0set size=1u=0 flag=1
main y=0
pushing
came out i=1
waiting
i=1set size=1u=1 flag=1
(Output is not terminating and i think it went into dead lock can anyone help why it is not
terminating)