平凡的类
#include <iostream>
#include <thread>
#include <functional>
using namespace std;
struct Task
{
int i = 100;
void do_job(void)
{
std::cout << "Hello Task::f ! i=" << i << std::endl;
}
void do_job2(int n)
{
std::cout << "Hello Task::f ! n=" << n << std::endl;
}
};
typedef function<void()> fun;
int main()
{
Task task;
auto worker = std::bind(&Task::do_job, task);
auto worker2 = std::bind(&Task::do_job2, task, 123456);
thread t(worker);
thread t2(worker2);
t.join();
t2.join();
}
非平凡的类
禁止复制的类
#include <iostream>
#include <thread>
#include <mutex>
#include <functional>
using namespace std;
struct Task
{
int i = 100;
void do_job(void)
{
std::cout<< "Hello Task::f ! i=" << i << std::endl;
}
//不再使用bind语法
static void run(void* obj_this)
{
static_cast<Task*>(obj_this)->do_job();
}
mutex m_mutex;//这个成员禁止拷贝
};
typedef function<void()> fun;
int main()
{
Task task;
auto worker = std::bind(&Task::run, &task);
thread t(worker);
t.join();
std::cout << "Hello World!\n";
}