Nick_F
Nick_F

Reputation: 1121

Multithreads - passing arguments and receiving results

I am trying various options on working with threads. I wrote the code below, but it does not work as expected. How can I fix the code, so that the main function will correctly display the product?

using System;
using System.Threading;

namespace MultiThreads
{
    class Program
    {
        static int prod;
        public static void Main(string[] args)
        {
            Thread thread = new Thread(() => Multiply(2, 3));
            thread.Start();         
            for(int i = 0; i < 10; i++) { // do some other work until thread completes
                Console.Write(i + " ");
                Thread.Sleep(100);
            }
            Console.WriteLine();

            Console.WriteLine("Prod = " + prod); // I expect 6 and it shows 0
            Console.ReadKey(true);
        }

        public static void Multiply(int a, int b)
        {
            Thread.Sleep(2000);
            prod = a * b;
        }
    }
}

Upvotes: 1

Views: 54

Answers (1)

Alchemy
Alchemy

Reputation: 445

Ignoring the fact that you should be using non-blocking tasks, volatile properties and other coroutine principals, the immediate reason your program does not work as intended is because you didn't re-join the child thread back into the parent. See Join

Without the join, the Console.WriteLine("Prod = " + prod); occurs before the assignment prod = a * b;

static int prod;
static void Main(string[] args)
{
    Thread thread = new Thread(() => Multiply(2, 3));
    thread.Start();
    for (int i = 0; i < 10; i++)
    { // do some other work until thread completes
        Console.Write(i + " ");
       Thread.Sleep(100);
    }
    thread.Join(); // Halt current thread until the other one finishes.
    Console.WriteLine();

    Console.WriteLine("Prod = " + prod); // I expect 6 and it shows 0
    Console.ReadKey(true);
}

public static void Multiply(int a, int b)
{
    Thread.Sleep(2000);
    prod = a * b;
}

Upvotes: 1

Related Questions