run two tasks in parallell and make them start 2 more threads each, up until a total of 16 threads are running. then print "hello" in all threads. in csharp

main.cs
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create two tasks that start with 2 threads each
            Task task1 = Task.Factory.StartNew(() => StartThreads(2));
            Task task2 = Task.Factory.StartNew(() => StartThreads(2));

            // Wait for the tasks to complete
            Task.WaitAll(task1, task2);

            Console.WriteLine("Hello from all threads!");
            Console.ReadKey();
        }

        static void StartThreads(int threadsToStart)
        {
            int runningThreads = 0;
            while (runningThreads < 16)
            {
                // Start new thread
                Thread thread = new Thread(() => Console.WriteLine("Hello from thread: " + Thread.CurrentThread.ManagedThreadId));

                // Increment count of running threads
                Interlocked.Increment(ref runningThreads);

                // Start the thread
                thread.Start();

                // Wait for the thread to start
                Thread.Sleep(100);

                // Decrement count of running threads
                Interlocked.Decrement(ref runningThreads);

                // Increment count of threads started
                threadsToStart++;

                // Ensure that we don't start more than 16 threads
                if (threadsToStart > 16)
                {
                    break;
                }

                // Wait before starting more threads
                Thread.Sleep(1000);
            }
        }
    }
}
1643 chars
57 lines

This code creates two tasks that start with two threads each. The StartThreads method is called by each task and creates new threads in a loop until 16 threads are running altogether. The Interlocked class is used to ensure that the count of running threads is incremented/decremented atomically, as this operation is not thread-safe. Finally, the code prints "Hello" from all threads and waits for a key press before exiting.

gistlibby LogSnag