CHAPTER 92. OPENMP CHAPTER 92. OPENMP
Chapter 92
OpenMP
OpenMP is one of the simplest ways to parallelize simple algorithms.
As an example, let’s try to build a program to compute a cryptographicnonce. In my simplistic example, thenonceis a
number added to the plain unencrypted text in order to produce a hash with some specific features. For example, at some
step, the Bitcoin protocol requires to find suchnonceso the resulting hash contains a specific number of consecutive zeroes.
This is also called “proof of work”^1 ( i.e., the system proves that it did some intensive calculations and spent some time for
it).
My example is not related to Bitcoin in any way, it will try to add numbers to the “hello, world!” string in order to find such
number that when “hello, world!
Let’s limit our brute-force to the interval in 0..INT32_MAX-1 (i.e.,0x7FFFFFFEor 2147483646).
The algorithm is pretty straightforward:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "sha512.h"
int found=0;
int32_t checked=0;
int32_t __min;
int32_t __max;
time_t start;
#ifdef GNUC
#define min(X,Y) ((X) < (Y)? (X) : (Y))
#define max(X,Y) ((X) > (Y)? (X) : (Y))
#endif
void check_nonce (int32_t nonce)
{
uint8_t buf[32];
struct sha512_ctx ctx;
uint8_t res[64];
// update statistics
int t=omp_get_thread_num();
if (__min[t]==-1)
__min[t]=nonce;
if (__max[t]==-1)
__max[t]=nonce;
__min[t]=min(__min[t], nonce);
__max[t]=max(__max[t], nonce);
// idle if valid nonce found
(^1) wikipedia