join()函数用于等待一个线程结束,从而保证主线程能够在所有线程都执行完成后再继续执行。该函数可用于多个线程之间的同步和协调。
以下是一个简单的示例,演示了如何使用join()函数等待一个线程结束:
#include <iostream>
#include <thread>
void thread_function()
{
std::cout << "Thread Function\n";
}
int main()
{
std::thread t1(thread_function);
// 等待t1线程执行完毕
t1.join();
std::cout << "Main Thread\n";
return 0;
}
在上面的示例中,创建了一个名为t1的线程,然后调用join()函数,等待t1线程执行完毕。一旦t1线程执行完毕,主线程才会继续执行。
join()函数还可以用于等待多个线程执行完毕。下面是一个示例,演示了如何等待多个线程执行完毕:
#include <iostream>
#include <thread>
void thread_function(int id)
{
std::cout << "Thread " << id << " Function\n";
}
int main()
{
const int num_threads = 5;
std::thread threads[num_threads];
// 创建多个线程并等待它们执行完毕
for (int i = 0; i < num_threads; i++)
{
threads[i] = std::thread(thread_function, i);
}
for (int i = 0; i < num_threads; i++)
{
threads[i].join();
}
std::cout << "Main Thread\n";
return 0;
}
在上面的示例中,创建了五个线程并用一个循环等待它们执行完毕。这样确保了所有线程都执行完毕后,主线程才会继续执行。