C++多线程编程1

来看一个例子,

#include <iostream>
#include <thread>
int a = 0;
int b = 0;
void printMessage() {
for (int i = 0; i < 100; i++)
{
std::cout << "Hello from thread A! "<< a++ << std::endl;
}
}

void printMessage1() {
for (int i = 0; i < 100; i++)
{
std::cout << "Hello from thread B! "<< b++ << std::endl;
}
}

int main() {
// 创建一个线程,运行 printMessage 函数
std::thread myThread(printMessage);
std::thread myThread1(printMessage1);

// 等待线程完成
myThread.join();
myThread1.join();

std::cout << "Hello from main thread!" << std::endl;
return 0;
}

Execute 1st output:

Hello from thread A! Hello from thread B! 0
Hello from thread A! 1
Hello from thread A! 2
... ... //输出省略掉了
Hello from thread A! 98
Hello from thread A! 99
0
Hello from thread B! 1
Hello from thread B! 2
... ... //输出省略掉了
Hello from thread B! 98
Hello from thread B! 99
Hello from main thread!

Execute 2rd output:

Hello from thread A! Hello from thread B! 00
Hello from thread A! 1
Hello from thread A! 2
... ... //输出省略掉了
Hello from thread A! 98
Hello from thread A! 99
//这里有一个程序输出的空格
Hello from thread B! 1
Hello from thread B! 2
... ... //输出省略掉了
Hello from thread B! 98
Hello from thread B! 99
Hello from main thread!

可以看到两次输出不一致。实际上把循环加到1000,两个线程的交叉执行调用会更频繁。因为这里程序是并发(Concurrency)执行,即线程在一个核上以’时间切片’的方式交替执行[1]。

Hello from thread A! Hello from thread B! 0
Hello from thread B! 1
Hello from thread B! 1
... ... //输出省略掉了
Hello from thread B! 299
0
Hello from thread A! 1
Hello from thread A! 2
... ... //输出省略掉了
Hello from thread A! 154
Hello from thread A! 155Hello from thread B! 300
Hello from thread B! 301
... ... //输出省略掉了
Hello from thread B! 999
//这里有一个程序输出的空格
Hello from thread A! 156
Hello from thread A! 157
... ... //输出省略掉了
Hello from thread A! 999
Hello from main thread!

[1]参考C++ Concurrency in Action: Practical Multithreading第一章

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.