C++11创建线程的简单应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89110944

一 批量创建线程

1 代码

#include <stdio.h>
#include <stdlib.h>

#include <chrono>    // std::chrono::seconds
#include <iostream>  // std::cout
#include <thread>    // std::thread, std::this_thread::sleep_for
using namespace std;
void thfunc(int n)   //线程函数
{
    std::cout << "thfunc:" << n  <<  endl;
}
int main(int argc, const char *argv[])
{
    std::thread threads[5]; //批量定义5个thread对象,但此时并不会执行线程
    std::cout << "create 5 threads...\n";
    for (int i = 0; i < 5; i++)
        threads[i] = std::thread(thfunc, i + 1);   // 这里开始执行线程函数
     
    for (auto& t : threads)    //等待每个线程结束
        t.join();

    std::cout << "All threads joined.\n";

    return EXIT_SUCCESS;
}   

2 运行

[root@localhost test]# g++ -o test test.cpp -lpthread -std=c++11
[root@localhost test]# ./test
create 5 threads...
thfunc:1
thfunc:2
thfunc:3
thfunc:4
thfunc:5
All threads joined.

3 说明

先定义了5个线程对象,刚定义的时候并不会执行线程,然后将另外初始化构造函数的返回值赋给它们。创建的线程都是可连接线程,所以要用join来等待它们结束。多执行几次这个程序,就可以发现其打印的次序并不是每次都一样,这与CPU调度有关。

二 创建一个线程,不传参数

1 代码

#include <iostream>  
#include <thread>  
      
using namespace std;    //使用命名空间std
      
void th_function()  //子线程的线程函数
{  
    std::cout << "i am c++11 thread func" << std::endl;  
}  
      
int main(int argc, char *argv[])  
{  
    std::thread t(th_function);   //定义线程对象,并把线程函数指针传入
    t.join();  //等待线程结束
      
    return 0;  
}

2 运行

[root@localhost test]# g++ -o test test.cpp -lpthread -std=c++11
[root@localhost test]# ./test
i am c++11 thread func

3 说明

编译C++11的时候,要加上编译命令函数“-std=c++11”。这个例子中,先定义了一个线程对象,定义对象后马上会执行传入构造函数的线程函数,线程函数打印一行字符后结束,主线程会等待子线程结束。

三 创建一个线程,并传入整型参数

1 代码

#include <iostream>  
#include <thread>  
using namespace std;  
      
void thfunc(int n)   //线程函数
{  
    cout << "thfunc: " << n << "\n";     //这里n是1
}  
      
int main(int argc, char *argv[])  
{  
    thread t(thfunc,1);    //定义线程对象t,并把线程函数指针和线程函数参数传入
    t.join();  //等待线程对象t结束
      
    return 0;  
}  

2 运行

[root@localhost test]# g++ -o test test.cpp -lpthread -std=c++11
[root@localhost test]# ./test
thfunc: 1

3 说明

创建线程的时候,把一个整数作为参数传给构造函数。

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/89110944