function与bind基本用法
本帖最后由 古月不傲 于 2021-1-11 19:13 编辑#include <iostream>
#include <functional>
#include <pthread.h>
class Thread
{
public:
Thread(const std::function<void()> &cb) : m_cb(cb), m_pid(0)
{
}
public:
void start()
{
pthread_create(&m_pid, nullptr, run, this);
}
void join()
{
pthread_join(m_pid, nullptr);
}
private:
static void *run(void *arg)
{
Thread *pThis = static_cast<Thread *>(arg);
pThis->m_cb();
return nullptr;
}
private:
pthread_t m_pid;
std::function<void()> m_cb;
};
void test1()
{
std::cout << "test1" << std::endl;
}
void test2(int a)
{
std::cout << "test2" << std::endl;
}
void test3(int a, int b)
{
std::cout << "test3" << std::endl;
}
int main(void)
{
Thread t1(test1);
Thread t2(std::bind(test2, 3));
Thread t3(std::bind(test3, 5, 6));
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
return 0;
}
页:
[1]