Reputation: 331
I'm trying to create a code to brute-force a random string but running it on one thread makes it take too long (as expected). I'm fiddling around with pthreads and this is what i've come up with:
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 );
}
}
}
Now, I need someway of signaling that one of the threads has already guessed the string correctly and terminate the others. I read some of the documentation for pthread library and couldn't find anything. Any help is appreciated.
PS: I know the brute-force algorithm is by far not the best.
Upvotes: 1
Views: 1331
Reputation: 95354
Clumsy but workable in your case:
Add a DONE flag in global scope. Set it when a result is found by any thread. Make each thread's loop be dependent on the flag.
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
}
Your main program can still do the join to collect finished pthreads, and then continue on with any work it might want to do on the guessed answer.
Upvotes: 1
Reputation: 41301
As long as you don't want your program to run any longer after the answer is found, you can just call exit(0) from the thread which found the answer.
do
{
// ...
}
while ( STRING!= guess );
std::cout << guess << std::endl;
std::exit(0);
Upvotes: 1