I'm trying make a simple async call using C++. My problem is that my code executing sync and use block functions. I want a async and non-blocking program.
First time, I wrote a little code in C++ to test my logic, so the program ends before thread so this not works. But on the Xcode on iOS project I can write C++ code without main
function, on the Final Objective part is detailed it.
#include <iostream>
#include <string>
#include <chrono>
#include <future>
using namespace std;
void call_from_async()
{
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << "Async call" << endl;
}
int main(void) {
printf("1\n");
std::future<void> fut = std::async(std::launch::async, call_from_async);
// std::async(std::launch::async,call_from_async);
printf("2\n");
return 0;
}
Output:
1
2
Desired output:
1
2
Async Call
Final Objective
I've a Swift project and I must call C++ async functions. To do it, I want call a C++ function from Swift and pass a pointer function to get the callback when process has been finished. To start the project I just wrote a little code to call C++ function and leave the work make on background, when work is finished back to Swift throught callback function. I don't make a callback function yet, before I want test the async functions.
Swift code
// ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
printFromCPP()
print("1")
call_async_function()
print("2")
}
}
// Ex_iOS_CPP_Swift-Bridging-Header.h
#ifdef __cplusplus
extern "C" {
#endif
#include "Foo.h"
#ifdef __cplusplus
}
#endif
// Foo.h
#ifndef Foo_h
#define Foo_h
void printFromCPP();
void call_async_function();
#endif /* Foo_h */
// Foo.cpp
#include <iostream>
#include <future>
#include <unistd.h>
#include "Ex_iOS_CPP_Swift-Bridging-Header.h"
using namespace std;
void called_from_async() {
sleep(3);
cout << "Async call" << endl;
}
void call_async_function() {
// std::future<void> fut = std::async(std::launch::async, called_from_async);
std::future<void> result( std::async(called_from_async));
}
void printFromCPP() {
cout << "Hello World from CPP" << endl;
}
Output
Hello World from CPP
1
Async call
2
Desired output
Hello World from CPP
1
2
Async call