如何在完成工作后停止所有pthread

How to stop all pthreads when one has completed its work?

本文关键字:pthread 工作      更新时间:2023-10-16

我正试图创建一个代码来强制执行随机字符串,但在一个线程上运行它会花费太长时间(正如预期的那样)。我正在摆弄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:我知道暴力算法还不是最好的。

只要你不想让你的程序在找到答案后再运行,你就可以从找到答案的线程调用exit(0)。

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

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

在全局范围中添加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,然后继续对猜测的答案进行任何工作。