1.全局函数作为传参入口
#include <iostream>
#include <thread>
#include <string>void ThreadMain(int p1,float p2,std::string str)
{std::cout << "p1:" << p1 << std::endl;std::cout << "p2:" << p2 << std::endl;std::cout << "str:" << str << std::endl;
}int main()
{std::thread th;{float f = 12.1f;th = std::thread(ThreadMain, 101, f, "test_str");}th.join();return 0;
}
2.传递指针
①传递空间已经销毁
②多线程共享访问一块空间
③传递的指针变量的生命周期小于线程
#include <iostream>
#include <thread>
#include <string>class Para
{public:Para() { std::cout << "Create Para!" << std::endl; }Para(const Para &p) { std::cout << "Copy Para!" << std::endl; }~Para() { std::cout << "Drop Para!" << std::endl; }std::string name;
};void ThreadMainPtr(Para* p)
{std::cout << "name:" << (*p).name << std::endl;}int main()
{{Para p;p.name = "Test!";std::thread th(ThreadMainPtr, &p);th.join();}getchar();return 0;
}
3.传递引用
在线程引用中需要使用ref函数引用参数
#include <iostream>
#include <thread>
#include <string>class Para
{public:Para() { std::cout << "Create Para!" << std::endl; }Para(const Para &p) { std::cout << "Copy Para!" << std::endl; }~Para() { std::cout << "Drop Para!" << std::endl; }std::string name;
};void ThreadMainRef(Para &p)
{std::cout << "name:" << p.name << std::endl;
}int main()
{{Para p;p.name = "Test!";std::thread th(ThreadMainRef, std::ref(p));th.join();}getchar();return 0;
}
4.成员函数作为线程入口
#include <iostream>
#include <thread>
#include <string>class MyThread
{public:void Main() { std::cout << "name:" << name << ",age:" << age << std::endl; }int age;std::string name;
};int main()
{MyThread myth;myth.age = 10;myth.name = "Test";std::thread th(&MyThread::Main, myth);th.join();return 0;
}
5.lambda表达式作为线程入口
#include <iostream>
#include <thread>int main()
{std::thread th([](int i) {std::cout << "test lambda:" << i << std::endl; },123);th.join();return 0;
}