1、全局函数传入thread
# include <iostream>
# include <thread>
# include <string>
void threadWork ( std:: string content, int counts)
{
for ( int i = 0 ; i < counts; ++ i) {
std:: cout << content << i << std:: endl;
}
}
int main ( ) {
std:: thread worker ( threadWork, std:: string ( "work on thread, index: " ) , 10 ) ;
worker. join ( ) ;
return 0 ;
}
2、类成员函数传入thread
# include <iostream>
# include <thread>
# include <string>
class MyClass {
public :
void doSomething ( std:: string content, int counts) {
for ( int i = 0 ; i < counts; ++ i) {
std:: cout << content << i << std:: endl;
}
}
} ;
int main ( ) {
MyClass* obj = new MyClass;
std:: thread worker ( & MyClass:: doSomething, obj, std:: string ( "doSomething on thread, index: " ) , 10 ) ;
worker. join ( ) ;
return 0 ;
}
3、lambda表达式(匿名函数)传入thread
# include <iostream>
# include <thread>
# include <string>
int main ( ) {
std:: thread worker (
[ ] ( std:: string content, int counts)
{
for ( int i = 0 ; i < counts; ++ i) {
std:: cout << content << i << std:: endl;
}
} , std:: string ( "lambda on thread, index: " ) , 10 ) ;
worker. join ( ) ;
return 0 ;
}