首页 > 解决方案 > 如果任何一个线程完成并获得可访问状态,则多线程检查可访问性,然后通过 priting 状态退出主线程

问题描述

多个线程访问同一函数以检查可访问性,如果任何一个线程完成并获得可访问状态,然后通过 priting 状态退出主线程,不要等待其他线程完成。在下面的代码中,我在 main 中使用了 while() 循环,请建议我是否有其他方法不使用 main 中的 while 循环

    #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";
        }
    }
        
    
        

标签: c++multithreadingc++14detach

解决方案


您能否在 condition_variable 的帮助下重写代码?

以下是我如何实施 Igor Tandetnik 的使用std::condition_variable建议;在文件范围内

#include <mutex>
#include <condition_variable>
mutex m;
condition_variable cv;

- 然后更改++g_completed_thread_cnt;

        { lock_guard<mutex> lk(m); ++g_completed_thread_cnt; }
        cv.notify_one();

和改变

        while(g_isLocalNetwork ==false && g_completed_thread_cnt!=vsize)
        {
            ;
        }
        cout<<"vsize="<<vsize<<" and g_completed_thread_cnt="<<g_completed_thread_cnt<<endl;

        unique_lock<mutex> lk(m);
        cv.wait(lk, [vsize]{ return g_isLocalNetwork || g_completed_thread_cnt==vsize; });
        cout<<"vsize="<<vsize<<" and g_completed_thread_cnt="<<g_completed_thread_cnt<<endl;
        lk.unlock();

推荐阅读