以下简单代码(C++ 11)将在Mac OS和Linux上运行:
#include <thread>
#include <chrono>
#include <iostream>
void threadFunction() {
for (int cc=0; cc < 10000000; ++cc) {
if (cc%1000000 == 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
}
}
int main(int argc, char **argv) {
std::thread threads[10];
for (int tt = 0; tt < 10; ++tt) {
threads[tt] = std::thread(threadFunction);
}
// Wait for the threads to complete
for (int tt = 0; tt < 10; ++tt) {
printf("About to join %d\n", tt);
std::cout.flush();
threads[tt].join();
printf("Joined %d\n", tt);
std::cout.flush();
} …Run Code Online (Sandbox Code Playgroud)