C++ 11 线程简单示例

C++ 11 thread simple example

本文关键字:简单 线程 C++      更新时间:2023-10-16

我是 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 mainn";
    //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

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

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

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 mainn";
-----------------------------------------------------------
mtx.unlock();

参考这个

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

特别是看看第一行输出的末尾。

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 mainn";

以前

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

您也可以使用支架:

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;
} 

刷新流应该可以解决问题:)

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

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