c++创建线程
普通函数创建线程
#include <iostream>
#include <thread>
void func()
{
std::cout << "hello world!" << std::endl;
}
int main()
{
std::thread thread_tmp(&func);
thread_tmp.join();
return 0;
}
类外部创建类非静态成员函数的线程
class Test
{
public:
void func()
{
std::cout << "hello world!" << std::endl;
}
};
int main()
{
Test my_test;
std::thread thread_tmp =std::thread(std::bind(&Test::func, my_test));
thread_tmp.join();
system("pause");
return 0;
}
类外部创建类静态成员函数的线程
#include<iostream>
#include<thread>
class A
{
public:
static void fun()
{
std::cout<< "hello world";
}
};
int main()
{
std::thread t=std::thread(A::fun);
system("pause");
return 0;
}
类内部创建线程
静态函数
class Test
{
public:
Test()
{
init();
}
static void init()
{
std::thread thread_tmp(&func);
thread_tmp.join();
}
static void func()
{
std::cout << "hello world!" << std::endl;
}
};
int main()
{
Test my_test;
system("pause");
return 0;
}
非静态函数(std::bind)
class Test
{
public:
Test()
{
init();
}
void init()
{
std::thread thread_tmp = std::thread(std::bind(&Test::func,this));
thread_tmp.join();
}
void func()
{
std::cout << "hello world!" << std::endl;
}
};
int main()
{
Test my_test;
system("pause");
return 0;
}
编辑于 2019-08-12