C++多线程

Linux下C++ 多线程编程:入门

2018-01-04  本文已影响20人  EVANMORE

一个简单的多线程例子

#include <iostream>
#include <thread>

void foo(int i)
{
    std::thread::id this_id = std::this_thread::get_id();
    
    std::cout << "thread_func: id = " << this_id << ", " << i << std::endl;
}

int main()
{
    for (uint8_t i = 0; i < 4; i++)
    {
        std::thread t(foo, i);
        
        t.detach();
    }
    
    getchar();
    return 0;
}

这个程序里面创建了4个线程,每次创建的时候分别传递一个标签进去,运行一次,我们可能会看到如下的输出,

thread_func: id = 139708503934720, 3
thread_func: id = 139708512327424, 2
thread_func: id = 139708520720128, 1
thread_func: id = 139708529112832, 0

可以看到这些线程的调度运行的顺序并不一定按照创建线程的先后,它有可能是任意的;

多运行几次后,我们可能会看到如下的打印

thread_func: id = thread_func: id = 140703835129600, 2
140703851915008, 0
thread_func: id = 140703843522304, 1
thread_func: id = 140703826736896, 3

显然的,第0个线程在打印的时候被第2个线程中断了,所以打印出来是这样。

那怎么解决这个问题呢,我们就引入了线程锁

引入线程锁

修改后的程序如下

#include <iostream>
#include <thread>
#include <mutex>

std::mutex g_display_mutex;

void foo(int i)
{
    std::thread::id this_id = std::this_thread::get_id();
    
    g_display_mutex.lock();
    std::cout << "thread_func: id = " << this_id << ", " << i << std::endl;
    g_display_mutex.unlock();
}

int main()
{
    for (uint8_t i = 0; i < 4; i++)
    {
        std::thread t(foo, i);
        
        t.detach();
    }
    
    getchar();
    return 0;
}

这样打印消息的时候就再也不会出现中断的情况了。

detach和join

C++有两种方式来等待线程结束

  1. detach在这里表示启动的线程自己在后台运行,当前的代码继续运行,不等待新的线程结束
  2. join的方式实在线程运行完成后再继续往下运行,所以如果对之前的代码再做修改如下
int main()
{
    for (int i = 0; i < 4; i++)
    {
        std::thread t(foo, i);
        t.join();
        std::cout << "main: " << i << std::endl;    
    }
    
    getchar();
    return 0;
}

这个时候每次main函数打印的时候都会等待新创建的线程运行完毕,所以固定的会答应如下

thread_func: id = 139945708939008, 0
main: 0
thread_func: id = 139945708939008, 1
main: 1
thread_func: id = 139945708939008, 2
main: 2
thread_func: id = 139945708939008, 3
main: 3

关于线程的异常终结

假如说以detach的方式,让线程在后台运行,那么线程的实例和线程本身就分离开了;有可能出现一种场景,

处理这种问题的方法可以有两种

class foo 
{
public:
    foo();
    ~foo();
    
private:
    std::thread t;
};

foo::foo()
{
    t = std::thread([] {
        std::thread::id this_id = std::this_thread::get_id();
        std::cout << "thread: sleep for 3s! " << std::endl;
        sleep(3);
        g_display_mutex.lock();
        std::cout << "thread id = " << this_id << std::endl;
        g_display_mutex.unlock();
    });
}

foo::~foo()
{
    std::cout << "destructor called" << std::endl;
    
    if (t.joinable())
    {
        std::cout << "joinable" << std::endl;

        t.join();
    }
}

int main()
{
    foo m_foo;
    return 0;
}

运行打印的结果如下,

destructor called
joinable
thread: sleep for 3s!
thread id = 139909607855872
上一篇 下一篇

猜你喜欢

热点阅读