multiple threads accessing same function to check reachability if any one thread completed and got reachable status then exit from main by priting the status dont wait for other threads to complete. in the below code i have use while() loop inside main please suggest me is there any other way without using while loop in main
#include<iostream>
#include<thread>
#include<unistd.h>
#include<string>
#include<string.h>
#include<vector>
using namespace std;
enum sraChkReturnCode
{
Server_Chk_Success, // server check is success
Server_Not_Reachable, // Server is not reachable
Server_Reachable, // server is reachable
};
bool g_isLocalNetwork = false;
int g_completed_thread_cnt=0;
int checkReachability(std::string strServer)//this function is timetaking function
{
sleep(2);
if(strServer=="WHATSAPP")
return Server_Reachable;
else
return Server_Not_Reachable;
}
void ThreadFunction(std::string strServer)
{
int Local= Server_Not_Reachable;
cout<<"Thread function starts\n";
Local = checkReachability(strServer);
if(Local==Server_Reachable)
{
g_isLocalNetwork = true;
}
++g_completed_thread_cnt;
cout<<"\ncompleted_thread_cnt="<<g_completed_thread_cnt<<endl;
}
int main()
{
vector<string>vecServers{"INSTAGRAM","FACEBOOK","TWITTER","YOUTUBE","WHATSAPP","GOOGLE","EDGE","TELEGRAM","FIREFOX"};
int vsize=vecServers.size();
for (auto& strServer: vecServers)
{
std::thread th(ThreadFunction, strServer);
th.detach();
}
while(g_isLocalNetwork ==false && g_completed_thread_cnt!=vsize)
{
;
}
cout<<"vsize="<<vsize<<" and g_completed_thread_cnt="<<g_completed_thread_cnt<<endl;
if (g_isLocalNetwork == true)
{
cout<<"\nConnection reachable\n";
}
else
{
cout<<"\nConnection not reachable\n";
}
}