如何在完成工作后停止所有线程?

时间:2014-10-29 23:43:08

标签: c++ parallel-processing pthreads brute-force

我试图创建一个强制随机字符串的代码,但是在一个线程上运行它会花费太长时间(如预期的那样)。我正在摆弄pthreads,这就是我想出的:

void*
bruteForce ( void* ARGS )
{
    args *arg = ( args * ) ARGS;
    string STRING= arg->STRING;
    string charSet = arg->charSet;
    string guess = arg->guess;

    char c;
    int size;
    int pos;
    int lenght;
    int j = 0;
    char CHAR[STRING.length ( )];
    size = charSet.length ( );

    do
    {
        for ( j = 0; j < STRING.length ( ); j++ )
        {
            pos = rand ( ) % size;
            CHAR[j] = charSet[pos];
            guess = string ( CHAR );
            //cout << guess[j];
        }
        //cout << guess << endl;
    }
    while ( STRING!= guess );

}

int
main ( int argc, char** argv )
{

    srand ( ( unsigned ) ( time ( NULL ) ) );

    const int NUMBER_OF_THREADS = 10;

    args arg;
    ifstream myFile;
    string STRING;
    string charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    string guess;

    pthread_t threads[NUMBER_OF_THREADS];
    void* status;

    arg.charSet = charSet;
    arg.STRING= STRING;

    char c;
    int size;
    int pos;
    int lenght;
    int j = 0;

    myFile.open ( "string.txt" );

    getline ( myFile, STRING);
    size = charSet.length ( );


    int rc;

    //Creating threads for cracking the string
    for ( int i = 0; i < NUMBER_OF_THREADS; i++ )
    {
        rc = pthread_create ( &threads[i], NULL, bruteForce, ( void* ) &arg );
        if ( rc )
        {
            cout << "Couldnt create thread";
            exit ( 1 );
        }
    }


    //Joining threads
    for ( int i = 0; i < NUMBER_OF_THREADS; i++ )
    {
        rc = pthread_join ( threads[i], &status );
        if ( rc )
        {
            cout << "thread number " << i << " was unable to join: " << rc << endl;
            exit ( 1 );
        }
    }
}

现在,我需要发信号通知其中一个线程已正确猜出字符串并终止其他线程。我阅读了pthread库的一些文档,但无法找到任何内容。任何帮助表示赞赏。

PS:我知道蛮力算法到目前为止还不是最好的。

2 个答案:

答案 0 :(得分:1)

只要您不希望程序在找到答案后再运行,您就可以从找到答案的帖子中拨打exit(0)

do
{
    // ...
}
while ( STRING!= guess );
std::cout << guess << std::endl;
std::exit(0);

答案 1 :(得分:1)

笨拙但在你的情况下可行:

在全局范围内添加DONE标志。在任何线程找到结果时设置它。 使每个线程的循环依赖于标志。

 bool DONE=false; // set to true to stop other threads

 void*bruteForce ( void* ARGS )
 {   ...
     do
     {  <try a string>
     }
     while ( !DONE && STRING!= guess );
     DONE=true; // set redundantly but that doesn't hurt
 }

您的主程序仍然可以执行联接以收集已完成的pthread,然后继续执行它可能要对猜测答案执行的任何工作。