C ++ 11线程简单的例子

时间:2013-12-30 15:47:18

标签: c++ multithreading c++11 iostream

我是c ++的新手,我正在研究一些c ++跨平台线程教程。我正在研究这个问题:http://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/

并且正在尝试执行以下代码:

#include <iostream>
#include <thread>

static const int num_threads = 10;

//This function will be called from a thread

void call_from_thread(int tid) {
    std::cout << "Launched by thread " << tid << std::endl;
}

int main() {
    std::thread t[num_threads];

    //Launch a group of threads
    for (int i = 0; i < num_threads; ++i) {
        t[i] = std::thread(call_from_thread, i);
    }

    std::cout << "Launched from the main\n";

    //Join the threads with the main thread
    for (int i = 0; i < num_threads; ++i) {
        t[i].join();
    }

    return 0;
}

我得到的输出如下,我无法理解为什么:

syd@syd-HP-Compaq-dx7500-Microtower:~/Desktop$ ./ref
Launched by thread Launched by thread Launched by thread Launched by thread Launched by thread 201
Launched by thread 5

Launched by thread 6
4
Launched by thread 7
3

Launched by thread 8
Launched from the main
Launched by thread 9

我知道这些数字每次都是随机的,但有时候我没有显示数字,我想知道为什么?

4 个答案:

答案 0 :(得分:15)

他们都在那里。由于控制台输出以模糊的随机顺序发生,它们只是被破坏了。

特别要看一下第一行输出的结尾。

答案 1 :(得分:12)

您需要做的就是添加一个互斥锁并将其锁定在正确的位置:

std::mutex mtx;

-

void call_from_thread(int tid) {
    mtx.lock();
-----------------------------------------------------------
    std::cout << "Launched by thread " << tid << std::endl;
-----------------------------------------------------------
    mtx.unlock();
}

-

mtx.lock();
-----------------------------------------------------------
std::cout << "Launched from the main\n";
-----------------------------------------------------------
mtx.unlock();

refer to this

答案 2 :(得分:3)

中的IO(cout)存在竞争条件
std::cout << "Launched by thread " << tid << std::endl;

实际上,没有cout(“由线程发起”,tid,std :: endl)排序的保证。它的行为如下:

std::cout << "Launched by thread " ;
cout<< tid ;
cout<< std::endl;

您可以将 call_from_thread 更改为:

void call_from_thread(int tid) {
    std::cout << std::string("Launched by thread " + std::to_string(tid) + "\n");
}

下一点是

t[i] = std::thread(call_from_thread, i);

创建线程时,在创建时将调用函数 call_from_thread

所以最好移动

std::cout << "Launched from the main\n";

//Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
    t[i] = std::thread(call_from_thread, i);
}

您也可以使用holders

mutex g_i_mutex;  // protects cout

void call_from_thread(int tid) {
    lock_guard<mutex> lock(g_i_mutex);
    cout << "Launched by thread " ;
    cout<< tid ;
    cout<< std::endl;
} 

答案 3 :(得分:-2)

Flushing stream应该可以解决问题:)

以下行:std::cout << "Launched by thread " << tid << std::endl;

更改为:std::cout << "Launched by thread " << tid << std::endl << std::flush;