一、多线程小实例
#include <thread>
#include <iostream>
void foo() {
std::cout << "Hello world" << std::endl;
}
int main() {
std::thread thread(foo); // 启动线程foo
thread.join(); // 等待线程执行完成
std::cout << "I am coming !" << std::endl;
return 0;
}
C++11 多线程库 使用std;;thread 实例,此处为一个线程,运行下来跟普通的没什么区别。
运行,程序输出:
Hello world
I am comming !
创建一个双线程的例子:
#include<thread>
#include<iostream>
#include<chrono>
using namespace std::chrono;
void foo(const char*name)
{
std::this_thread::sleep_for(milliseconds(1000));
std::cout << "hello " << name <<std::endl;
for (int i = 0; i < 10; i++)
{
std::cout << i << std::endl;
}
}
void fooo(const char*name)
{
std::cout << "hello " << name << std::endl;
for (int i = 10; i < 20; i++)
{
std::cout << i << std::endl;
}
}
int main()
{
std::thread thread(foo,"thread");
std::thread thread2(fooo, "thread2");
thread.join();
thread2.join();
std::cout << "I am comming " << std::endl;
return 0;
}
运行,程序输出:
其中std::this_thread::sleep_for(milliseconds(1000));
为使该线程等待1000ms再执行,估程序先执行了thread2,此时可看成增加线程后与普通函数的不同。
具体函数解析,见下一篇