IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> C++知识库 -> thread -> 正文阅读

[C++知识库]thread

目录

线程安全

创建线程

std::thread 创建线程 (线程不安全)

互斥量(mutex) 原子变量(atomic)

std::thread

thread_local


线程安全

就是多线程访问时,采用了加锁机制,当一个线程访问该类的某个数据时,进行保护,其他线程不能进行访问直到该线程读取 完,其他线程才可使用。不会出现数据不一致或者数据污染。”

创建线程

std::thread 创建线程 (线程不安全)

#include <iostream>
#include <thread>
using namespace std;
//计数全局变量
long cnt = 0;

//计数程序
void counter()
{
	for (int i = 0; i < 100000; ++i)
	{
		cnt++;
        cnt--;
	}
}

int main(int argc, char* argv[])
{
	std::thread t1(counter);
    std::thread t2(counter);
    t1.join();
    t2.join();
    cout << "current cnt = " << cnt<<endl;
	return 0;
}

?连续执行两次结果分别是:current cnt = -852 和 current cnt = 27,即这段代码是线程不安全的。

互斥量(mutex) 原子变量(atomic)

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
std::mutex mtx;
//计数全局变量
long cnt = 0;

//计数程序
void counter()
{
    cout << "当前进程 ID" <<getpid() << pthread_self() 
    << "当前线程 ID: " <<this_thread::get_id() <<endl;
	for (int i = 0; i < 100000; ++i)
	{
        mtx.lock();                // 添加线程锁
		cnt++;
        cnt--;
        mtx.unlock();             // 去除线程锁
	}
}

int main(int argc, char* argv[])
{
	std::thread t1(counter);
    std::thread t2(counter);
    t1.join();
    t2.join();
    cout << "current cnt = " << cnt<<endl;  // 结果:current cnt = 0
	return 0;
}

通过mutex加互斥锁 ,但使用mtx.lock()上锁后,若在mtx.unlock()解锁之前出现return 等结束该函数,意味着程序无法执行到解锁,那么就导致死锁。

条件变量(condition_variable), 信号量(semaohore)

promise future

std::packged_task std::async

生产者消费者模型

线程池的实例

thread_local

thread_local变量是C++ 11新引入的一种存储类型。它会影响变量的存储周期(Storage duration),C++中有4种存储周期:

  1. automatic
  2. static
  3. dynamic
  4. thread

有且只有thread_local关键字修饰的变量具有线程周期(thread duration),这些变量(或者说对象)在线程开始的时候被生成(allocated),在线程结束的时候被销毁(deallocated)。并且每 一个线程都拥有一个独立的变量实例(Each thread has its own instance of the object)。thread_local 可以和staticextern关键字联合使用,这将影响变量的链接属性(to adjust linkage)。

那么,哪些变量可以被声明为thread_local?以下3类都是ok的

  1. 命名空间下的全局变量
  2. 类的static成员变量
  3. 本地变量

下面引用《C++ Concurrency in Action》书中的例子来说明这3种情况:

thread_local int x;  //A thread-local variable at namespace scope
class X
{
    static thread_local std::string s; //A thread-local static class data member
};
static thread_local std::string X::s;  //The definition of X::s is required

void foo()
{
    thread_local std::vector<int> v;  //A thread-local local variable
}

既然每个线程都拥有一份独立的thread_local变量,那么就有2个问题需要考虑:

  1. 各线程的thread_local变量是如何初始化的
  2. 各线程的thread_local变量在初始化之后拥有怎样的生命周期,特别是被声明为thread_local的本地变量(local variables)

下面的代码可以帮助回答这2个问题。

#include <thread>

thread_local int g_n = 1;
static int g_nn=1;
void f()
{   g_nn++;
    g_n++;
    printf("f() id=%d, thread_local n=%d, static g_nn=%d\n", std::this_thread::get_id(),g_n,g_nn);
}

void foo()
{
    thread_local int i=0;
    printf("foo() id=%d, n=%d\n", std::this_thread::get_id(), i);
    i++;
}

void f2()
{
    foo();
    foo();
}

int main()
{
    g_nn++;
    g_n++;
    f();               //id=1,g_n=3,主线程中,线程id为1, 在f()中g_n = 3
    std::thread t1(f); //id=2, n=2,新建线程id为2,新线程初始化g_n为1,通过f()中的g_n++计算,返回的g_n=2
    std::thread t2(f); //id=3, n=2,新建线程id为3,新线程初始化g_n为1,通过f()中的g_n++计算,返回的g_n=2
    t1.join();
    t2.join();
    f();               //id=1, n=4 ,回到主线程,id=1,f()再次g_n++,返回g_n=4

    f2();              //foo() id=1, n=0,foo() id=1, n=1 回到主线程,id依旧为1,在主线程中初始化i=0
    std::thread t4(f2);//foo() id=4, n=0,foo() id=4, n=1 新建线程id=4,初始化i=0
    std::thread t5(f2);//foo() id=5, n=0,foo() id=5, n=1 新建线程id=5,初始化i=0
    t4.join();
    t5.join();
    f2();              // 回到主线程id=1,再次执行两次i++,即返回i=2,i=3
    return 0;
}

结果:

f() id=1, thread_local n=3, static g_nn=3
f() id=2, thread_local n=2, static g_nn=4
f() id=3, thread_local n=2, static g_nn=5
f() id=1, thread_local n=4, static g_nn=6
foo() id=1, n=0
foo() id=1, n=1
foo() id=4, n=0
foo() id=4, n=1
foo() id=5, n=0
foo() id=5, n=1
foo() id=1, n=2
foo() id=1, n=3

可见,thread_local是规定每次新建线程时,重新初始化该变量,它的声明周期贯穿一个线程的创建和结束。而static 则始终进行一次变量初始化,对所有的线程保持变量共享。

  C++知识库 最新文章
【C++】友元、嵌套类、异常、RTTI、类型转换
通讯录的思路与实现(C语言)
C++PrimerPlus 第七章 函数-C++的编程模块(
Problem C: 算法9-9~9-12:平衡二叉树的基本
MSVC C++ UTF-8编程
C++进阶 多态原理
简单string类c++实现
我的年度总结
【C语言】以深厚地基筑伟岸高楼-基础篇(六
c语言常见错误合集
上一篇文章      下一篇文章      查看所有文章
加:2022-05-19 11:50:18  更:2022-05-19 11:51:21 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/13 3:27:55-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码