C++11多线程编程 第一章: 创建线程的三种不同方式

C++11 Multithreading – Part 1 : Three Different ways to Create Threads

Varun January 20, 2015 C++11 Multithreading – Part 1 : Three Different ways to Create Threads2018-08-18T15:04:02+00:00C++ 11c++11 ThreadsMultithreading

In this article we will discuss how to create threads in C++11 using std::thread.

 

Introduction to C++11 Thread Library

Original C++ Standard supported only single thread programming. The new C++ Standard (referred to as C++11 or C++0x) was published in 2011. In C++11 a new thread library is introduced.

Compilers Required:  
Linux: gcc 4.8.1 (Complete Concurrency support)
Windows: Visual Studio 2012 and MingW

How to compile on Linux: g++ –std=c++11 sample.cpp -lpthread

Thread Creation in C++11

In every C++ application there is one default main thread i.e. main() function. In C++ 11 we can create additional threads by creating objects of std::thread class.
Each of the std::thread object can be associated with a thread.

Header Required :

 

1

#include <thread>

 

What std::thread accepts in constructor ?

We can attach a callback with the std::thread object, that will be executed when this new thread starts. These callbacks can be,

1.) Function Pointer
2.) Function Objects
3.) Lambda functions

Thread objects can be created like this,

 

1

std::thread thObj(<CALLBACK>);

New Thread will start just after the creation of new object and will execute the passed callback in parallel to thread that has started it.
Moreover, any thread can wait for another to exit by calling join() function on that thread’s object.

Lets look at an example where main thread will create a separate thread. After creating this new thread, main thread will print some data on console and then wait for newly created thread to exit.

Lets implement above using three different callback mechanism,

Creating a thread using Function Pointer

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#include <iostream>

#include <thread>

 

void thread_function()

{

    for(int i = 0; i < 10000; i++);

        std::cout<<"thread function Executing"<<std::endl;

}

 

int main()  

{

    

    std::thread threadObj(thread_function);

    for(int i = 0; i < 10000; i++);

        std::cout<<"Display From MainThread"<<std::endl;

    threadObj.join();    

    std::cout<<"Exit of Main function"<<std::endl;

    return 0;

}

 

Creating a thread using Function Objects

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

#include <iostream>

#include <thread>

class DisplayThread

{

public:

    void operator()()     

    {

        for(int i = 0; i < 10000; i++)

            std::cout<<"Display Thread Executing"<<std::endl;

    }

};

 

int main()  

{

    std::thread threadObj( (DisplayThread()) );

    for(int i = 0; i < 10000; i++)

        std::cout<<"Display From Main Thread "<<std::endl;

    std::cout<<"Waiting For Thread to complete"<<std::endl;

    threadObj.join();

    std::cout<<"Exiting from Main Thread"<<std::endl;

    return 0;

}

 

Creating a thread using Lambda functions

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#include <iostream>

#include <thread>

int main()  

{

    int x = 9;

    std::thread threadObj([]{

            for(int i = 0; i < 10000; i++)

                std::cout<<"Display Thread Executing"<<std::endl;

            });

            

    for(int i = 0; i < 10000; i++)

        std::cout<<"Display From Main Thread"<<std::endl;

        

    threadObj.join();

    std::cout<<"Exiting from Main Thread"<<std::endl;

    return 0;

}

 

Differentiating between threads

Each of the std::thread object has an associated ID and we can fetch using,

Member function, gives id of associated thread object i.e.

 

1

std::thread::get_id()

To get the identifier for the current thread use,

 

1

std::this_thread::get_id()

If std::thread object does not have an associated thread then get_id() will return a default constructed std::thread::id object i.e. not any thread.

std::thread::id is a Object, it can be compared and printed on console too. Let’s look at an example,

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

#include <iostream>

#include <thread>

void thread_function()

{

    std::cout<<"Inside Thread :: ID  = "<<std::this_thread::get_id()<<std::endl;    

}

int main()  

{

    std::thread threadObj1(thread_function);

    std::thread threadObj2(thread_function);

 

    if(threadObj1.get_id() != threadObj2.get_id())

        std::cout<<"Both Threads have different IDs"<<std::endl;

 

        std::cout<<"From Main Thread :: ID of Thread 1 = "<<threadObj1.get_id()<<std::endl;    

    std::cout<<"From Main Thread :: ID of Thread 2 = "<<threadObj2.get_id()<<std::endl;    

 

    threadObj1.join();    

    threadObj2.join();    

    return 0;

}

转自: https://thispointer.com/c-11-multithreading-part-1-three-different-ways-to-create-threads/

 

ps:

在JAVA中习惯了类的编写, cpp的这种方式使用十分不便, 我一般都是使用如下方式封装一下.

class MyThread{

void stop(); //里面标记一个原子变量_stop;

void run(); // 在循环里判断_stop是否置为true, 如果为true, 则停止执行.

void start(){

       std::thread myThread(&MyThread::run, this); //创建子线程执行run函数.
        if (myThread.joinable()) {
           myThread.detach(); // 与创建函数的对象分离, 否则对象析构时, 会调用线程的terminate终止线程执行. 
        }

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值