C++ 多线程实例

 使用C++实现多线程实例【ubuntu16.04环境 C++11】

需要引用头文件:`thread` 【C++11线程标准库】

注意:编译时 g++ -o main -lpthread -std=c++11

如果不添加编译选项:`lpthread`  则会报错:`collect2: error: ld returned 1 exit status`

C++ 多线程实例_第1张图片

 

 多线程代码实例

#include 
#include 

using namespace std;

thread::id main_thread_id = this_thread::get_id(); //获取当前线程的句柄id

void hello()  //测试单线程
{
    if (this_thread::get_id() == main_thread_id)
    {
        cout << "this is main thread" << endl;
    }
    else
    {
        cout << "this is not main thread" << endl;
    }
}
void p_thread(int n) //线程睡眠n s
{
    this_thread::sleep_for(chrono::seconds(n));
    cout << this_thread::get_id() << endl;
    fprintf(stdout, "thread have slpet in %d s\n", n);
}

int main()
{
    thread t(hello);
    cout << t.hardware_concurrency() << endl;
    cout << "native_handle:" << t.native_handle() << endl;
    t.join();
    thread a(hello);
    a.detach();   //从多线程中分离,允许独立执行

    cout << "+==============+" << endl;
    const int THREAD_NUM = 5;
    thread threads[5];     
    for (int i = 0; i < THREAD_NUM; i++)
    {
        //创建多线程句柄数组
        threads[i] = thread(p_thread,  1);
    }
    cout << "all thread are joining.." << endl;
    for (auto &th : threads)
    {
        th.join();  //阻塞执行当前线程
    }
    cout << "all thread are joined.." << endl;
}

输出结果:

2
native_handle:139718829721344
this is not main thread
+==============+
this is not main thread
139718821328640
thread have slpet in 1 s
139718812935936
thread have slpet in 2 s
139718829721344
thread have slpet in 3 s
139718804543232
thread have slpet in 4 s
139718796150528
thread have slpet in 5 s
all thread are joined..

 

你可能感兴趣的:(C++,多线程)