As I’ve stated many times before, I like to break things. While migrating a dozen or so WordPress websites from my old web server to a high-availability network of web servers I seem to be breaking them left and right! Luckily WP-CLI was here to save the day!

With a home network of 29+ devices a standard router from the store just doesn’t cut it for me. We have smart TV’s, game systems, phones, tablets, laptops, desktops, you name it and it’s probably connected to our wired or wireless network. Many standard routers can handle roughly 4-5 active devices concurrently before they start having issues. Even when devices are idly connected to the network they are still doing things in the background like checking for/performing updates for example.

I stumbled across an article today on HackRead that I could tell the writer clearly did not do their research (or math). Here’s an excerpt..

I’ve been blogging here for about 6 years now. In that time I’ve done a lot of overhauling on my website. Quite frankly, I’ve been doing it all wrong!

Often times when writing a server you will need to be able to handle multiple client connections at a time. To do this you will want to create a threaded server.

These are the WordPress plugins that, in my opinion, are worthy of being called top 10. I’m not putting them into any particular order.

If you’re hosting a website which has any sort of posting system (ie- forums, comments, etc..) then you are likely to receive a lot of spam if you leave yourself open to it. One simple way to stop spam in it’s tracks is to simply check visitors IP addresses against a DNSBL (DNS Blacklist).

I find myself recommending a lot of these tools & practices to friends and colleagues so I thought I would share some of my insight on the best tools and practices to use for good OPSEC.

I’ll go over some of the tools that I personally use, then briefly describe how some of them can be used together to make your OPSEC practices a little easier and more streamlined.

In C# there are various reasons that you may have for needing to thread your applications out. I’m won’t go into detail what reasons you would have for doing so, I am only going to explain how that is done. This article goes over a complete example of C# threading, and then explains each piece of the code to help break the process down for you. It is important to note that I am still learning C#, and may not be showing you the best way to handle this. Please feel free to offer me corrections via email and I will update accordingly.

The example code will send chunks of 10,000 numbers to 4 worker threads. The worker threads will find all prime numbers in the given chunk and print them to the screen. There is no guarantee that prime numbers will be listed in order, so one may want to pop the output into another program to sort them out, this wasn’t the main focus of the program’s duties. The full example can be found at the bottom of the post.

static void Main(string[] args)
{
    int i;
    int initThreadCount = Process.GetCurrentProcess().Threads.Count;
    bool num = int.TryParse(args[0], out i);
    if( i < 0 )
    {
        Console.WriteLine("Starting point must be 0 or greater!");
    }
    while ( i <= Int32.MaxValue && i >= 0 )
    {
        if( Process.GetCurrentProcess().Threads.Count-initThreadCount <= 4 )
        {
            Thread t = new Thread(() => checkBlockForPrime(i, i + 9999));
            t.Start();
            if (Int32.MaxValue - 10000 <= i)
            {
                i = Int32.MaxValue - 10000;
            }
            else
            {
                if (i == Int32.MaxValue)
                {
                    Console.WriteLine("I have reached the maximum value of an int.");
                    break;
                }
                else
                {
                    i = i + 10000;
                }
            }
        }
    }

The above code sample is the Main(), it takes a single argument (ref- Main(string[] args)) which should be an integer that it will start the count at. The program will fail to run if an integer is not passed as the first (and only) argument to the program.

The variable i is an integer which is used to keep track of what number the program is on. It is incremented for each block of numbers passed to worker threads. The argument given to the program is what defines the variable. This integer is defined in lines 3 and 5 of the example code above.

int i;

bool num = int.TryParse(args[0], out i);

On line 4 I set the integer initThreadCount to the number of threads that had already been started on the program’s execution. I did this so that I could do a comparison in the while statement which would allow me to accurately find how many threads are put to use for checking prime numbers (ref- if( Process.GetCurrentProcess().Threads.Count-initThreadCount <= 4 )).

Main runs a while loop which runs as long as i is less than Int32.MaxValue (the maximum integer on a 32bit system) and i is less than 0 (ie- while ( i <= Int32.MaxValue && i >= 0 )).

If you wish to compile your code only for 64 bit, then you can replace Int32.MaxValue with Int64.MaxValue and it should all work the same.

Inside of the while loop the program checks that no more than 4 threads are running aside from the initial thread count from when the program started. If there are 4 or more threads then it will wait until threads are freed. If there are less than 4 threads working on the task then a new thread will be created with a block of 10,000 numbers.

The new thread is created with: Thread t = new Thread(() => checkBlockForPrime(i, i + 9999)); and then started with t.Start();.

Next the program needs to increment the value of i. I have added a few checks which could cause some non-unique output when it comes to the last 10,000 numbers leading up to Int32.MaxValue. Since this is just an example of threading I’m not concerned with some slight logic flaws, but it might be fun for you to try to work them out.

First my program checks if Int32.MaxValue - 10000 is less than or equal to i. If it is then we are in the last 10,000th block and the program will set i to the value of Int32.MaxValue - 10000 to avoid looping i into the negatives. If this statement is not true then the program checks to see if i is equal to Int32.MaxValue, it cannot continue to process anything higher than that so if this condition is ever met it should break out of the loop and end execution of the program. If this statement is false then i is simply incremented by 10,000 (ref- i = i + 10000).

Each time a new thread is created in the main loop, it calls a function called checkBlockForPrime, this function is defined and explained in the sample below.

public static void checkBlockForPrime(int start, int end)
{
    int i = start;
    while( i <= end )
    {
        if (checkPrime(i) == true)
        {
            Console.WriteLine(i);
        }
        i = i + 1;
    }
}

checkBlockForPrime accepts two arguments, the beginning and end integers that it should check against. Essentially our Main() gives this function two numbers every time it creates a new thread, and this function inclusively checks whether numbers in that range are prime. If it finds a prime number, the number is printed to the screen. Simple enough right?

The next sample is the checkPrime function that is used above, it simply checks whether or not the given integer is prime. If the number is prime it returns true, and if not it returns false.

public static bool checkPrime(int num)
{
    // Test whether the parameter is a prime number.
    if ((num & 1) == 0)
    {
        if (num == 2)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    for (int i = 3; (i * i) <= num; i += 2)
    {
        if ((num % i) == 0)
        {
            return false;
        }
    }
    return true;
}

The full code below can be copied into a Visual Studio CLI project and compiled there. If you are on Linux just save this to a file (prime.cs for example) and compile it with Mono (gmcs prime.cs</span>).

/*
** Project Name: PrimeTime
** Author: Robert Whitney <[email protected]>
** Description: Uses multi-threading to find prime numbers in generated chunks and then prints all primes to the screen.
**    Processes about 873,190 numbers/second in blocks of 10,000 using 4 worker threads.
**    Tested on Windows 8.1 x64, w/ Intel Core i7 2600 (3.40GHz) processor.
**    Max integer limited to value of Int32.MaxValue (2,147,483,647)
*/
/* Include libraries for the project */
using System;
using System.Threading;
using System.Diagnostics;

namespace PrimeTime
{
    class PrimeTime
    {
        static void Main(string[] args)
        {
            int i;
            int initThreadCount = Process.GetCurrentProcess().Threads.Count;
            bool num = int.TryParse(args[0], out i);
            if( i < 0 )
            {
                Console.WriteLine("Starting point must be 0 or greater!");
            }
            while ( i <= Int32.MaxValue && i >= 0 )
            {
                if( Process.GetCurrentProcess().Threads.Count-initThreadCount <= 4 )
                {
                    Thread t = new Thread(() => checkBlockForPrime(i, i + 9999));
                    t.Start();
                    if (Int32.MaxValue - 10000 <= i)
                    {
                        i = Int32.MaxValue - 10000;
                    }
                    else
                    {
                        if (i == Int32.MaxValue)
                        {
                            Console.WriteLine("I have reached the maximum value of an int.");
                            break;
                        }
                        else
                        {
                            i = i + 10000;
                        }
                    }
                }
            }
            Console.WriteLine("Cannot process numbers larger than " + Int32.MaxValue + " and will not process numbers smaller than 0");
        }

        public static void checkBlockForPrime(int start, int end)
        {
            int i = start;
            while( i <= end )
            {
                if (checkPrime(i) == true)
                {
                    Console.WriteLine(i);
                }
                i = i + 1;
            }
        }
        public static bool checkPrime(int num)
        {
            // Test whether the parameter is a prime number.
            if ((num & 1) == 0)
            {
                if (num == 2)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            for (int i = 3; (i * i) <= num; i += 2)
            {
                if ((num % i) == 0)
                {
                    return false;
                }
            }
            return true;
        }
    }
}
Robert Whitney
I'm a geek, gamer and breaker of things.
Opinions expressed here, even 💩 ones, are my own and do not represent those of my employer or associates.
Referral Links

Using my referral links is the best way to help me pay for my projects and development servers and get something out of it for yourself.

Copyright©2011 - 2018, Robert Whitney; All rights reserved.
Aeon Address: WmtnQAoEJsfbcjyMJLmfW8SJ3j5VCGGjX4k3hHrc4XbhVcz6dxifHs65h2w3y5gq8Qf4D4tgzb6VxEtggSq5hR8s1CzN1cLeK