Place Holder Products Code
Bash MySQL
Notes Return of the Fed Login
Admin Control Panel Email Control Panel Product Control Panel Debug Info Beacon Create Snippet Tag Control Panel

Code

*More fully fledged applications can be found on the Products page. The Bash page is dedicated to fully commented oneliners, and a MySQL quick reference is available here.


/* threaded_find_primes.cpp
 *	- Will Bergen - 2018
 *	- Simple, trivially threaded exercise.  Each thread will try 1000 random numbers
 *		and report on its progress, or any found primes.
 *	- Also, *fun with terminal colors*
 *	- Primes will be between 0 and RAND_MAX
 *	- compile with: g++ threaded_find_primes.cpp -std=c++11 -g -lpthread
 *
 */


#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cstdint>
#include <math.h>
#include <string>
#include <thread>

using namespace std;



// Thread data passing struct:
struct result
{
	int res;
};


void isPrime(uint64_t *n, result &r);
void *doWork(void *r);


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

	// If not enough args:
	if (argc < 2)
	{
		printf("Usage:\n\tfind_primes <#threads>\n");
		return 0;
	}

	// If not a number:
	int num_threads;
	string s = argv[1];
	try {
		num_threads = stoi(s);
	}
	catch(std::invalid_argument& e)
	{
		printf("Invalid number of threads!\n");
		printf("Usage:\n\tfind_primesX <#threads>\n");
		return 1;
	}

	// Go:
	pthread_t threads[num_threads];
	printf("Starting \033[0;32m%i\033[0m Threads!\n", num_threads);

	// Create the Threads:
	int i;
	int resp;
	for (i=0;i<num_threads;++i)
	{
		resp = pthread_create(&threads[i], NULL, doWork, (void *)(uintptr_t)i);
		if (resp)
		{
			cout << "Error creating thread: " << resp << endl;
		} else {
			printf("Created \033[1;31mThread %i\033[0m\n", i);
		}
	}

	// Wait for termination:
	int j;
	for (j=0;j<num_threads;++j)
	{
		pthread_join(threads[j],NULL);
	}
	return 0;

}

// Thread:
void *doWork(void *t)
{
	// Per thread seed:
	srand(time(NULL));

	int i;
	uint64_t n;
	long tid = (long)t;
	result r = {0};

	for (i=0;i<1000;++i)
	{
		// Choose a random, reset r:
		n = rand();
		r.res = 0;

		// Test:
		isPrime((uint64_t *)n, r);

		// Report:
		if (r.res == 1)
		{
			printf("\033[1;31mThread %li\033[0m found prime %lu\n", tid, n);
		}

		if (i%50 == 0 && i != 0)
		{
			printf("\033[1;31mThread %li\033[0m has tested %i numbers...\n", tid, i);
		}

	}

	pthread_exit(NULL);
}

// Simple Primality test:
void isPrime(uint64_t *n, result &r)
{
	int i;
	uint64_t j;
	result l_r = {1};

	for (i=2;i<=floor((uint64_t)n / 2); ++i)
	{
		j = i;
		if((uint64_t)n%j == 0)
		{
			// Factor found, not prime!
			l_r.res = 0;
			break;
		}
	}

	// Update:
	r = l_r;
}