0

I’m in the process of trying to teach myself Threading in c# and I’ve been reading a number of tutorials, questions and examples. I’ve successfully(*it seems to work) implemented threading into much bigger application but they are some areas which just feel very gray to me.

I’ve tried to put together a small console application, as point of discussion and to try and answer the questions posed. I’m not an experienced programmer – so if I’ve committed some mortal sins here I sincerely apologise. Feel free to point them out as well in bid to improve my programming skills. Hopefully the questions I raise here will help me and others trying to understand threading.

  1. The first question is – if I called randomNums.GenrateRandomNumbers() inside ThreadStart(), would that be considered unsafe. I’m concluding it would be as PrintRandomCNumbers() is being called from the other threads and it would mean the object would be in very much undetermined state?

  2. If I wanted to call randomNums.GenrateRandomNumbers, what would be the thread safe way to call it? How and where would I implement the locks, would I use write, multiple read lock?

  3. When I run this application, each thread correctly outputs the contents of randomNums, is there a scenario (multiple processors or cores), where given this implementation the information wouldn’t be present to output but the copy of the object reference still be in scope. I.e. randomNums becomes null.

  4. If there is not hardware scenario, how would I manipulate this example to generate a scenario like this. I.e. Threadmanger has the Randomnums object reference but it just end up pointing at uninitiated object, but attempt to initiate the object. (I had a similar problem to this in my bigger application.)

  5. What is best design practice for getting data into and out of thread?

  6. When designing a thread to start, is good practice to manage the start and top of thread inside the object or outside the object.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Using System Threading for theads;
using System.Threading;

namespace ThreadingExamples
{
    class Program
    {

        static void Main(string[] args)
        {
            MyApplication app = new MyApplication();
            app.Start();
        }


        public class MyApplication
        {
            private RandomNumbers randomNums;


            public MyApplication()
            {

            }

            public void Start()
            {
                randomNums = new RandomNumbers();
                randomNums.GenrateRandomNumbers();
                randomNums.PrintRandomcNumbers();

                ThreadManager newThreadMan = new ThreadManager(randomNums);

                Console.ReadLine();
            }

        }

        public class ThreadManager
        {
            private RandomNumbers randomNums;
            private Thread[] newThreads;
            private int threadCount;

            public ThreadManager(RandomNumbers newRandomNums)
            {
                threadCount = 3;
                randomNums = newRandomNums;
                newThreads = new Thread[threadCount];
                for (int i = 0; i < threadCount; i++)
                {
                    newThreads[i] = new Thread(ThreadStart);
                    newThreads[i].Start();
                }
            }
            public void ThreadStart()
            {
                randomNums.PrintRandomcNumbers();
            }

        }

        public class RandomNumbers
        {
            private Random rnd = new Random();
            private int numberToStore;
            private int[] randomNumbers;

            public RandomNumbers()
            {
                numberToStore = 12;
                randomNumbers = new int[numberToStore];
            }

            public void GenrateRandomNumbers()
            {
                for (int i = 0; i < numberToStore; i++)
                {
                    randomNumbers[i] = rnd.Next(1,13);
                }
            }
            public void PrintRandomcNumbers()
            {
                StringBuilder outputString = new StringBuilder();
                for (int i = 0; i < numberToStore; i++)
                {
                    outputString = new StringBuilder("The Random Numbers in position ");
                    outputString.Append(i.ToString());
                    outputString.Append("is the number: ");
                    outputString.Append(randomNumbers[i].ToString());

                    Console.WriteLine(outputString);
                }
            }
        }
    }
}
2
  • 4
    Ask only one question. You cannot learn threading from an SO question, there are many excellent books available. Dec 14, 2013 at 13:22
  • Well learning threading on SO aside, I’ve tried to focus number of questions to the point, rather than one open ended question. Dec 14, 2013 at 14:52

1 Answer 1

1
  1. As written the calling of random numbers is actually safe enough, bad practice since random numbers will change based on the thread executing at the time, Something to keep in mind here, if numbers to store changes in each thread, say one is 6 and another thread has a number of 12, then both threads will have a list of random numbers that has 12 numbers in it, and the one with 6 will only change the first 6 elements in the list, not resize the list itself.

  2. The simple explanation for how to safely change data from an internal thread is don't. I would actually find a different way to do this. If you find yourself needing to display different random numbers in each thread for instance generate a different list and pass it to the thread.

  3. Since you aren't instantiating a new object as written this program will work fine, the data might not be exactly what you would expect, but there is not a situation where the data will not be there.

  4. Actually this would be simple to force to fail, simple instantiate a new list every time the GenerateRandomNumbers function is called. This can cause runtime issues when one thread is at the point in it's cycle that it generates a new list, and another is looking for item 7 on that list, which isn't there because the new list is not initialized.

    public void GenrateRandomNumbers()
        {
            randomNumbers=new List<int>();
            for (int i = 0; i < numberToStore; i++)
            {
                randomNumbers[i] = rnd.Next(1,13);
            }
        }
    
  5. One of the things i have found when using threading is to make all your objects immutable, this eliminates the need to be careful about reassigning values in a thread because to put it simply it cannot be done. It does cause you to have to think about how you can accomplish what you are trying to accomplish without changing a value, but that's actually a good way to program, and will make your threading experience much better.

  6. A thread is essentially a fire and forget program, it goes and does it's own thing regardless of where or when it was called, and has the ability to interact with all running programs. Since this is true it doesn't really matter where you start the thread at, what matters is how that thread interacts with whatever you are running. I have always found the best practice when using threads is only implement a thread when you absolutely have to. To do a multi-threaded application you should be planning on making it multi-threaded in the design stages. Think very carefully about what each thread should do, and always be aware of how it will interact with the other running threads.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.