I have used the tasks in c# in this way:
static async Task<string> DoTaskAsync(string name, int timeout)
{
var start = DateTime.Now;
Console.WriteLine("Enter {0}, {1}", name, timeout);
await Task.Delay(timeout);
Console.WriteLine("Exit {0}, {1}", name, (DateTime.Now - start).TotalMilliseconds);
return name;
}
public Task DoSomethingAsync()
{
var t1 = DoTaskAsync("t2.1", 3000);
var t2 = DoTaskAsync("t2.2", 2000);
var t3 = DoTaskAsync("t2.3", 1000);
return Task.WhenAll(t1, t2, t3);
}
but I need to do the some in c .
There is a way to migrate this code in c ?
Thanks !
CodePudding user response:
A more or less direct translation would probably use C std::future
s returned by std::async
.
Disclaimer: I don't have bit of C# knowledge and just read about its Task
s a bit just now. I think this is what you are going for.
- In C we use
std::chrono::duration
s instead of plainint
s. The resolution of the clocks is often much higher than milliseconds, so I selected to go for whatever duration thestd::chrono::steady_clock
supports. You can thereby pass it astd::chrono::milliseconds
orstd::chrono::seconds
- and it will do the right thing.
#include <array>
#include <chrono> // clocks and durations
#include <format> // std::format
#include <future> // std::async
#include <iostream>
#include <string>
#include <thread> // std::this_thread::sleep_for
auto DoTaskAsync(std::string name, std::chrono::steady_clock::duration timeout)
{
return std::async(std::launch::async,
[name=std::move(name),timeout] {
auto start = std::chrono::steady_clock::now();
std::cout << std::format("Enter {0}, {1}\n", name, timeout);
std::this_thread::sleep_for(timeout);
std::cout << std::format("Exit {0}, {1}\n", name,
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start));
return name;
});
}
std::array<std::string, 3> DoSomethingAsync() {
using namespace std::chrono_literals;
auto t1 = DoTaskAsync("t2.1", 3000000000ns); // nanoseconds
auto t2 = DoTaskAsync("t2.2", 2000ms); // milliseconds
auto t3 = DoTaskAsync("t2.3", 1s); // seconds
return {t1.get(), t2.get(), t3.get()};
}