I am running on my Mac 2 similar code samples, one in C++, another in C#. 2 simple tasks that execute in parallel (or at least I want them to), one printing '+' in a loop, the other printing '-' in a loop. I was expecting the output from the 2 samples to be quite similar, but they are quite a bit different to my surprise.
C++ seems to truly run the tasks in parallel. I can see +- alternating nicely on every run, but C# seems to run one task for a while, then switch to the other task and run that for a while. Something like this:
C++: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
C# : ++++++++++---------++++++------
I understand assumptions cannot be made about how parallel threads are run, it's just curious to me that C++ produces such a nice result, consistently.
Thanks for your time!
C#:
using System;
using System.Threading.Tasks;
public class ConcurrentTasks
{
public static void Main(String[] args)
{
var task1 = Task.Run(()=>DemoTask("+"));
var task2 = Task.Run(()=>DemoTask("-"));
var res1 = task1.Result;
var res2 = task2.Result;
Console.WriteLine("\nResults:");
Console.WriteLine(res1);
Console.WriteLine(res2);
}
private static String DemoTask(String label)
{
for (int i = 0; i < 1000; i++)
{
Console.Write(label);
}
return label + " result";
}
}
// mcs ConcurrentTasks.cs
// mono ConcurrentTasks.exe
C++:
#include <iostream>
#include <sstream>
#include <future>
using namespace std;
string demoTask(char label)
{
for (int i = 0; i < 1000; i++)
{
cout << label;
}
stringstream ss;
ss << label;
ss << " result";
return ss.str();
}
int main()
{
auto task1 = async(demoTask, '+');
auto task2 = async(demoTask, '-');
auto res1 = task1.get();
auto res2 = task2.get();
cout << endl << "Results:" << endl;
cout << res1 << endl;
cout << res2 << endl;
return 0;
}
// g++ --std=c++14 -Wall ConcurrentTasks.cpp -o ConcurrentTasks.exe
// ./ConcurrentTasks.exe
Edit: I've changed the C# sample to use bare Thread and the result is the same.
C# with Thread:
using System;
using System.Threading;
public class ConcurrentTasks
{
public static void Main(String[] args)
{
var t1 = new Thread(() => DemoTask("+"));
var t2 = new Thread(() => DemoTask("-"));
t1.Start();
t2.Start();
}
private static String DemoTask(String label)
{
for (int i = 0; i < 1000; i++)
{
Console.Write(label);
}
return label + " result";
}
}