线程学习三:创建线程
目录
- 1. 线程创建
- 1.1 std::thread创建线程
- 1.1.1 用普通函数创建线程
- 1.1.2 用成员函数创建线程
- 1.1.3 用类对象创建线程
- 1.1.4 用Lambda表达式创建线程
- 1.2 pthread创建线程
- 1.1 std::thread创建线程
1. 线程创建
1.1 std::thread创建线程
-
- 用普通函数创建线程
-
- 用成员函数创建线程
-
- 用类对象创建线程
-
- 用Lambda表达式创建线程
1.1.1 用普通函数创建线程
#include
#include
void foo(int a)
{
std::cout << a << std::endl;
}
int main()
{
// Create and execute the thread
std::thread thread(foo, 10); // foo is the function to execute, 10 is the
// argument to pass to it
// Keep going; the thread is executed separately
// Wait for the thread to finish; we stay here until it is done
thread.join();
return 0;
}
// 编译方法: g++ -g test.cpp -o test -std=c++11 -lpthread
1.1.2 用成员函数创建线程
#include
#include
class Bar
{
public:
void foo(int a)
{
std::cout << a << std::endl;
}
};
int main()
{
Bar bar;
// Create and execute the thread
std::thread thread(&Bar::foo, &bar, 10); // Pass 10 to member function
// The member function will be executed in a separate thread
// Wait for the thread to finish, this is a blocking operation
thread.join();
return 0;
}
// 编译方法: g++ -g test.cpp -o test -std=c++11 -lpthread
1.1.3 用类对象创建线程
#include
#include
// 类要变成可调用对象需要重载操作符()
class Bar
{
public:
void operator()(int a)
{
std::cout << a << std::endl;
}
};
int main()
{
Bar bar;
// Create and execute the thread
std::thread thread(bar, 10); // Pass 10 to functor object
// The functor object will be executed in a separate thread
// Wait for the thread to finish, this is a blocking operation
thread.join();
return 0;
}
// 编译方法: g++ -g test.cpp -o test -std=c++11 -lpthread
1.1.4 用Lambda表达式创建线程
#include
#include
class Test
{
public:
Test(int m) : m_iCount(m) {}
~Test() {}
void init() {
// 用Lambda表达式创建线程。this是该匿名函数捕获的外部参数。()为空,表示该匿名函数没有参数
std::thread([this]() {
std::cout << "m_iCount = " << m_iCount << std::endl;
}).join();
}
private:
int m_iCount;
};
int main()
{
// 方法1:
auto lambda = [](int a) { std::cout << a << std::endl; };
// Create and execute the thread
std::thread thread(lambda, 10); // Pass 10 to the lambda expression
// The lambda expression will be executed in a separate thread
// Wait for the thread to finish, this is a blocking operation
thread.join();
// 方法2:在一个类中用匿名函数创建线程
Test test(5);
test.init();
return 0;
}
// 编译方法: g++ -g test.cpp -o test -std=c++11 -lpthread
1.2 pthread创建线程
int pthread_create (pthread_t *__restrict __newthread,
const pthread_attr_t *__restrict __attr,
void *(*__start_routine) (void *),
void *__restrict __arg)
// 第一个参数为指向线程标识符的指针。
// 第二个参数用来设置线程属性。
// 第三个参数是线程运行函数的起始地址。
// 第四个参数是运行函数的参数。
// pthread_create() 在调用成功完成之后返回零。其他任何返回值都表示出现了错误。
实例:
#include
#include
void* test(void* context)
{
std::cout << "hello, world" << std::endl;
}
int main()
{
pthread_t tid;
int ret = pthread_create(&tid, NULL, test, NULL);
pthread_join(tid, NULL);
return 0;
}
// 编译方法: g++ -g test.cpp -o test -lpthread
来自于
https://zhuanlan.zhihu.com/p/358428937