C++ thread学习一(利用C++11 thread创建线程)

之前几次学习多线程但都没有学到最后,今天重启C++多线程学习计划,希望可以坚持到最后。首先简单介绍一下进程以及线程。进程是系统资源分配的最小单位,线程是cpu执行的最小单位。简单来说,一个可执行程序运行起来就是一个进程,一个进程可能包含多个线程,一个进程一定有一个主线程,就相当于main函数,是程序的入口。

1. 创建一个线程,线程被创建后就立即开始执行

#include 
using namespace std;
#include "thread"
void threadTest()
{
    cout << "This is other thread\n";
}

int main(int argc, const char * argv[]) {
    // insert code here...
    
    thread mythread (threadTest);
    mythread.join();
    cout << "This is main thread\n";
    return 0;
}

结果:

C++ thread学习一(利用C++11 thread创建线程)_第1张图片

这里使用了thread.join函数,这时候主线程会被阻塞,等待mythread执行完才会继续执行。

2. 也可以使用thread.detach函数,这样主线程和子线程分离,主线程不再等待子线程执行,子线程成为守护线程,由C++运行时库进行管理。

#include 
using namespace std;
#include "thread"
#include 
void threadTest()
{
    sleep(2);
    cout << "This is other thread\n";
}

int main(int argc, const char * argv[]) {
    // insert code here...
    
    thread mythread (threadTest);
    mythread.detach();
    cout << "This is main thread\n";
    return 0;
}

结果:

可以看出,创建线程后调用detach函数,子线程和主线程分离,子线程休眠2秒,此时主线程继续执行结束并退出,所以子线程并没有输出结果。

3. 一个thread只可以调用join或者detach两者中的一个至多一次,未调用前thread.joinable()返回true表示当前thread此时可调用detach或者join,调用过后thread.joinable()返回false。

4. 使用类创建线程

由于thread参数必须是一个可调用类型,所以这个类必须重载()使其可调用。

#include 
using namespace std;
#include "thread"
#include 
class ThreadClass
{
public:
    void operator ()()
    {
        cout << "This is a thread created by a class\n";
    }
};

int main(int argc, const char * argv[]) {
    // insert code here...
    ThreadClass myclass;
    thread mythread (myclass);
    if(mythread.joinable())
    {
        mythread.join();
    }
    cout << "This is main thread\n";
    return 0;
}

结果:

也可以使用函数指针,传递类里面任意函数作为线程参数。 

格式为 thread(&className::function name, object, args)

#include 
using namespace std;
#include "thread"
#include 
class ThreadClass
{
public:
    void operator ()()
    {
        cout << "This is a thread created by a class\n";
    }
    void func(int x)
    {
        cout << "This is a thread created by a class method\n";
    }
};

int main(int argc, const char * argv[]) {
    // insert code here...
    ThreadClass myclass;
    int x = 1;
    thread mythread (&ThreadClass::func, myclass, x);
    if(mythread.joinable())
    {
        mythread.join();
    }
    cout << "This is main thread\n";
    return 0;
}

结果:

5. 使用lambda表达式创建线程

#include 
using namespace std;
#include "thread"
#include 
int main(int argc, const char * argv[]) {
    // insert code here...
    auto func = []{
        cout << "This a thread created by lambda function\n";
    };
    thread mythread (func);
    if(mythread.joinable())
    {
        mythread.join();
    }
    cout << "This is main thread\n";
    return 0;
}

结果:

 

你可能感兴趣的:(C++)