阅读量:106
在C++中创建线程的方法通常有两种:使用std::thread类或者使用POSIX线程库。
- 使用std::thread类:
#include
#include
void threadFunction() {
std::cout << "Hello from thread!" << std class="hljs-function">int main() {
std::thread myThread(threadFunction);
myThread.join(); //等待线程执行完毕
return 0;
}
- 使用POSIX线程库:
#include
#include
void* threadFunction(void* arg) {
std::cout << "Hello from thread!" << std class="hljs-keyword">return nullptr;
}
int main() {
pthread_t thread;
pthread_create(&thread, nullptr, threadFunction, nullptr);
pthread_join(thread, nullptr); //等待线程执行完毕
return 0;
}
需要注意的是,在C++11标准之后,推荐使用std::thread类来创建线程,因为它更易用且跨平台性更好。