How can I best "parallelize" a set of four nested for () loops in a Brute-Force attack?

I have the following homework task:
I need to iterate over the power of a 4-char passphrase with the following mask

% % @ @

(where is the numeric character, is the alpha character) @ %

in multiple threads using OpenMP.

Here is a snippet of code, but I'm not sure if it does the right thing:

int i, j, m, n;

const char alph[26] = "abcdefghijklmnopqrstuvwxyz";
const char num[10] = "0123456789";

#pragma omp parallel for private(pass) schedule(dynamic) collapse(4)
for (i = 0; i < 26; i++)
    for (j = 0; j < 26; j++)
        for (m = 0; m < 10; m++)
            for (n = 0; n < 10; n++) {
                pass[0] = alph[i];
                pass[1] = alph[j];
                pass[2] = num[m];
                pass[3] = num[n];

                /* Working with pass here */

            }

So my question is :
How do I specify the "parallel for" statement to split the range of code phrases between multiple cores?

Help is much appreciated.

+4
source share
1 answer

, alph num. pass , .

MWE :

//Compile with, e.g.: gcc -O3 temp.c -std=c99 -fopenmp
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int PassCheck(char *pass){
  usleep(50); //Sleep for 100 microseconds to simulate work
  return strncmp(pass, "qr34", 4)==0;
}

int main(){
  const char alph[27] = "abcdefghijklmnopqrstuvwxyz";
  const char num[11]  = "0123456789";
  char goodpass[5] = "----"; //Provide a default password to indicate an error state

  int i, j, m, n;

  #pragma omp parallel for collapse(4)
  for (i = 0; i < 26; i++)
  for (j = 0; j < 26; j++)
  for (m = 0; m < 10; m++)
  for (n = 0; n < 10; n++){
    char pass[4];
    pass[0] = alph[i];
    pass[1] = alph[j];
    pass[2] = num[m];
    pass[3] = num[n];
    if(PassCheck(pass)){
      //It is good practice to use `critical` here in case two
      //passwords are somehow both valid. This won't arise in
      //your code, but is worth thinking about.
      #pragma omp critical
      {
        memcpy(goodpass, pass, 4);
        goodpass[4] = '\0';
        //#pragma omp cancel for //Escape for loops!
      }
    }
  }

  printf("Password was '%s'.\n",goodpass);

  return 0;
}

dynamic , , . , . . , .

, , . , , .

#pragma omp cancel for OpenMP 4.0; , . , , , , .

, . pass[0], . , collapse(4). , , , . , , .

usleep?

usleep . ; parallelism, .

usleep, 0.003s 0.004s 4 . , parallelism . usleep 8.950s 2.257s 4 , parallelism.

, , , parallelism .

, , , - PassCheck. usleep() .

+2

Source: https://habr.com/ru/post/1691554/


All Articles