C++多线程----线程安全
当使用多线程时,可能存在同时访问一个变量,导致变量被污染问题,所以需要通过编程克服这个问题。
同时访问一个数据示例
采用多个线程,分别记数,然后查看最终计算结果,代码如下:
#include <iostream>
#include <thread>
#include <time.h>
//计数全局变量
long cnt = 0;
//计数程序
void counter()
{
for (int i = 0; i < 100000; ++i)
{
++cnt;
}
}
int main(int argc, char* argv[])
{
//开始计时
clock_t start = clock();
//创建线程
std::thread threads[100];
//调用记数函数
for (int i = 0; i != 100; ++i)
{
threads[i] = std::thread(counter);
}
//等待操作
for (auto& th : threads)
th.join();
clock_t finish = clock();
std::cout << "期望结