mardi 25 août 2020

call a callback function in a pthread function

I'm learning about callback functions in C++ and I'm trying to call a callback function in a pthread function wherein I'm passing the function as argument to pthread_create using reinterpret_cast and then cast it back inside pthread function. This is my code

#include <iostream>    
#include <atomic>
#include <algorithm>
#include <unistd.h>
#include <pthread.h>


std::atomic<int32_t> res(0);
using TCallback = std::function<void (int32_t)>;

void put_result(int32_t result) {
    res = result;
}

void time_consuming_func(TCallback Callback) {
    sleep(10);
    int32_t result = 10456456;
    Callback(result);
}

void* thread_func(void* arg) {
    TCallback callback = std::bind(reinterpret_cast<void (*) (int32_t)>(arg), std::placeholders::_1);
    time_consuming_func(callback);

    return nullptr;
}

int32_t main(int32_t argc, char* argv[]) {
    pthread_t p1;
    pthread_create(&p1, nullptr, thread_func, reinterpret_cast<void*>(put_result));
    
    std::cout << "before: " << res << std::endl;
    pthread_join(p1, nullptr);
    std::cout << "after: " << res << std::endl;

    return EXIT_SUCCESS;
}

I'm trying to compile the above program with the command g++ -Wall -pedantic-errors func_callback_demo.cpp -o func_callback_demo -std=c++11 -lpthread and it doesn't work, but if I remove -pedantic-errors and -wall flags it compiles.

Can somebody tell why this difference?

Aucun commentaire:

Enregistrer un commentaire