Threading

Write a very simple multi threaded program in C#.
1. The program should create two threads that each add data to the same list at the same time. Then after they are both done, print out the entire list.
2. So each thread should loop through 100 times adding the name of the thread doing the work to the list. For example, the first thread should add the string "thread1" to the shared list and the second thread should add the string "thread2" to the same list at the same time. This should result in a somewhat random ordering of the names "thread1" and "thread2" in the shared list that is printed out after both threads complete.
3. When a thread adds a name it should also print out its name and the current count of the list.
4. Make sure that each individual name addition is not interrupted by the other thread.

Questions by musclebai   answers by musclebai

Showing Answers 1 - 6 of 6 Answers

yogihanu

  • Mar 15th, 2008
 

Copy and past the below mentioned code to get the answer:

++++++++++
//Start copy from here

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;

namespace ThreadTest
{
    class Program
    {
        static ArrayList alist = new ArrayList();
        
        static void Main(string[] args)
        {
            //ArrayList alist = new ArrayList();
            ThreadStart job1 = new ThreadStart(Threadjob1);
            ThreadStart job2 = new ThreadStart(Threadjob2);
            Thread th1 = new Thread(job1);
            Thread th2 = new Thread(job2);
            th1.Start();
            th2.Start();

            int i = 0;
            while (i < 10)
            {
                Console.WriteLine("Main Thread 1 : {0}", i);
                alist.Add(string.Format("MainThread - {0}", i));
                Thread.Sleep(1000);
                i++;
            }
            for (int j = 0; j < alist.Count-1; j++)
            {
                Console.WriteLine("Name : {0}ttIndex : {1}",alist[j],j);
            }
            Console.Read();
         
        }
        static void Threadjob1()
        {
            int i = 0;
            while (i < 10)
            {
                Console.WriteLine("J O B 1 : {0}", i);
                alist.Add(string.Format("Job1 - {0}", i));
                Thread.Sleep(200);
                i++;
            }
           
        }
        static void Threadjob2()
        {
            int i = 0;
            while (i < 10)
            {
                Console.WriteLine("J O B 2 : {0}", i);
                alist.Add(string.Format("Job2 - {0}", i));
                Thread.Sleep(500);
                i++;
            }
        }
    }
}
//End copy here

  Was this answer useful?  Yes

JimmyJamJo

  • May 17th, 2008
 

See code below. In practice, the Thread.Sleep() is required - otherwise each thread will complete its work in a single time-slice before the other gets a chance to start. An improvement would be to create a "work item" class for the that would wrap "outputList" and "repeatCount" together in a single object, and use that with the ParameterizedThreadStart delegate.

-

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;

public class MyApp
{
    private static IList<string> outputList = new List<string>();

    static void Main()
    {
        const int threadCount = 2;
        const int repeatCount = 100;

        Thread[] threadList = new Thread[threadCount];

        // Create and start threads
        for (int i = 0; i < threadCount; i++)
        {
            threadList[i] = new Thread(new ParameterizedThreadStart(DoWork));
            threadList[i].Name = String.Format(CultureInfo.InvariantCulture, "Thread{0}", i);
            threadList[i].Start(repeatCount);
        }

        // Wait for them to do the business
        foreach (Thread t in threadList)
        {
            t.Join();
        }

        Console.WriteLine("All threads complete");

        // Output
        foreach (string s in outputList)
        {
            Console.WriteLine(s);
        }
    }

    private static void DoWork(object repeatCount)
    {
        Thread thisThread = Thread.CurrentThread;
        int numberOfWrites = (int)repeatCount;
        for (int i = 0; i < numberOfWrites; i++)
        {
            int listCount = 0;
            lock (outputList)
            {
                outputList.Add(thisThread.Name);
                listCount = outputList.Count;
            }

            Console.WriteLine("{0} - list count = {1}", thisThread.Name, listCount);

            // Sleep this thread to give the other thread(s) a fighting chance to get
            // in on the action
            Thread.Sleep(10);
        }
    }
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions