广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C++线程之thread详解
  • 728
分享到

C++线程之thread详解

2024-04-02 19:04:59 728人浏览 安东尼
摘要

目录1.创建线程2.守护线程3.可调用对象4.传参5.线程的移动和复制6.线程id7.互斥mutex总结1.创建线程 直接初始话thread类对象进行创建线程,创建线程后调用join

1.创建线程

直接初始话thread类对象进行创建线程,创建线程后调用join()方法,让主线程等待子线程完成工程。

#include <iOStream>
#include <thread>
void thread_function()
{
    std::cout << "thread function\n";
}
int main()
{
    std::thread t(&thread_function);   // t starts running
    std::cout << "main thread\n";
    t.join();   // main thread waits for the thread t to finish
    return 0;
}

2.守护线程

我们可以调用detach()方法,将线程变为守护线程,完成线程和主线程的分离。一旦线程分离,我们不能强迫它再次加入主线程,再次调用join()方法会报错的。

一旦分离,线程应该永远以这种方式存在。调用join()函数之前可以使用函数joinable()检查线程是否可以加入主线程,加强程序健壮性。

// t2.cpp
int main()
{
    std::thread t(&thread_function);
    std::cout << "main thread\n";
    if( t.joinable( ) ) 
        // t.join();
    // t.join();
    t.detach();
    return 0;
}

3. 可调用对象

线程可以调用

  • 函数指针
  • 类对象
  • lamda表达式

1.函数指针

就像之前举例的样子

2.类对象

#include <iostream>
#include <thread>
class MyFunctor
{
public:
    void operator()() {
        std::cout << "functor\n";
    }
};
int main()
{
    MyFunctor fnctor;
    // 这样是不能运行的,
    // std::thread t(fnctor);
    // 必须按照这样进行初始话。
    // MyFunctor fnctor;  Note that we had to add () to enclose the MyFunctor(). 
    std::thread t((MyFunctor())); // it's related to the function declaration convention in c++.
    std::cout << "main thread\n";
    t.join();
    return 0;
}

3.lamda表达式

#include <iostream>
#include <thread>
class MyFunctor
{
public:
    void operator()() {
        std::cout << "functor\n";
    }
};
int main()
{
    MyFunctor fnctor;
    // 这样是不能运行的,
    // std::thread t(fnctor);
    // 必须按照这样进行初始话。
    // MyFunctor fnctor;  Note that we had to add () to enclose the MyFunctor(). 
    std::thread t((MyFunctor())); // it's related to the function declaration convention in C++.
    std::cout << "main thread\n";
    t.join();
    return 0;
}

4. 传参

传参分为三种

1.值传递

2.引用传递

3.不复制,也不共享内存的传参方式move()

#include <iostream>
#include <thread>
#include <string>
void thread_function(std::string s)
{
    std::cout << "thread function ";
    std::cout << "message is = " << s << std::endl;
}
int main()
{
    std::string s = "Kathy Perry";
    // 1. 值传递
    std::thread t(&thread_function, s);
    // 2. 引用传递
    std::thread t(&thread_function, std::ref(s));
    // 3. 不复制,也不共享内存的传参方式`move()
    std::thread t(&thread_function, std::move(s));
    std::cout << "main thread message = " << s << std::endl;
    t.join();
    return 0;
}

5. 线程的移动和复制

// t5.cpp
#include <iostream>
#include <thread>
void thread_function()
{
    std::cout << "thread function\n";
}
int main()
{
    std::thread t(&thread_function);
    std::cout << "main thread\n";
    //  transfer the ownership of the thread by moving it:
    std::thread t2 = move(t);
    t2.join();
    return 0;
}

6.线程id

获取线程的id: this_thread::get_id()

总共有多少个线程:std::thread::hardware_concurrency()

程序

int main()
{
    std::string s = "Kathy Perry";
    std::thread t(&thread_function, std::move(s));
    std::cout << "main thread message = " << s << std::endl;
    std::cout << "main thread id = " << std::this_thread::get_id() << std::endl;
    std::cout << "child thread id = " << t.get_id() << std::endl;
    t.join();
    return 0;
}

输出

thread function message is = Kathy Perry
main thread message =
main thread id = 1208
child thread id = 5224

7. 互斥mutex

互斥可能是 C++ 中使用最广泛的数据保护机制,但重要的是构造我们的代码以保护正确的数据并避免接口中固有的竞争条件。互斥锁也有自己的问题,表现为死锁和保护太多或太少的数据

标准 C++ 库提供了std::lock_guard类模板,它实现 了互斥锁的RAII习惯用法。它在构造时锁定提供的互斥锁并在销毁时解锁它,从而确保始终正确解锁锁定的互斥锁。


#include <iostream>
#include <thread>
#include <list>
#include <alGorithm>
#include <mutex>
using namespace std;
// a global variable
std::list<int>myList;
// a global instance of std::mutex to protect global variable
std::mutex myMutex;
void addToList(int max, int interval)
{
	// the access to this function is mutually exclusive
	std::lock_guard<std::mutex> guard(myMutex);
	for (int i = 0; i < max; i++) {
		if( (i % interval) == 0) myList.push_back(i);
	}
}
void printList()
{
	// the access to this function is mutually exclusive
	std::lock_guard<std::mutex> guard(myMutex);
	for (auto itr = myList.begin(), end_itr = myList.end(); itr != end_itr; ++itr ) {
		cout << *itr << ",";
	}
}
int main()
{
	int max = 100;
	std::thread t1(addToList, max, 1);
	std::thread t2(addToList, max, 10);
	std::thread t3(printList);
	t1.join();
	t2.join();
	t3.join();
	return 0;
}

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!    

--结束END--

本文标题: C++线程之thread详解

本文链接: https://www.lsjlt.com/news/142818.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • C++线程之thread详解
    目录1.创建线程2.守护线程3.可调用对象4.传参5.线程的移动和复制6.线程id7.互斥mutex总结1.创建线程 直接初始话thread类对象进行创建线程,创建线程后调用join...
    99+
    2022-11-13
  • 详解C语言编程之thread多线程
    目录线程创建与结束线程的创建方式:线程的结束方式:join()detach()互斥锁<mutex> 头文件介绍std::mutex 介绍std::lock_guardst...
    99+
    2022-11-12
  • Python线程编程之Thread详解
    目录一、线程编程(Thread)1、线程基本概念1.1、什么事线程1.2、线程特征二、threading模块创建线程1、创建线程对象2、 启动线程3、 回收线程4、代码演示5、线程对...
    99+
    2022-11-12
  • c# Thread类线程常用操作详解
    目录创建线程 管理线程 销毁线程 创建线程 线程是通过扩展 Thread 类创建的。扩展的 Thread 类调用 Start() 方法来开始子线程的执行。 下面的程序演示...
    99+
    2022-11-11
  • C#多线程Thread使用示例详解
    本文实例为大家分享了C#多线程Thread使用的示例代码,供大家参考,具体内容如下 多线程: 线程生命周期状态图: C#线程优先级(概率高低): 基本使用示例: usin...
    99+
    2022-11-12
  • C#中Thread(线程)和Task(任务)实例详解
    目录线程一,使用Thread类启动线程和数据传输二,线程池ThreadPool类任务一,创建并启动任务二,连续任务三,资源冲突问题 总结线程 线程:对于所有需要等待的操作,...
    99+
    2022-11-13
  • C++学习之线程详解
    目录开篇线程的状态多线程的构建计算时间一、程序运行时间二、chrono共享资源和互斥锁condition_variable线程池总结开篇 多线程是开发中必不可少的,往往我们需要多个任...
    99+
    2022-11-12
  • C#多线程之线程池ThreadPool详解
    一、ThreadPool概述 提供一个线程池,该线程池可用于执行任务、发送工作项、处理异步 I/O、代表其他线程等待以及处理计时器。 创建线程需要时间。如果有不同的小任务要完成,就可...
    99+
    2022-11-13
  • C#线程开发之System.Thread类详解
    一、属性 CurrentContext    获取线程正在其中执行的当前上下文。ExecutionContext    获...
    99+
    2022-11-13
  • C# 异步多线程入门到精通之Thread篇
    上一篇:C# 异步多线程入门基础 下一篇:C# 异步多线程入门到精通之ThreadPool篇 Thread API 这里对 Thread 的一些常用 API 进行介绍,使用一些案例进...
    99+
    2022-11-12
  • C++中std::thread线程用法
    目录1:std::thread的基本用法2:std:: thread常用的成员函数 3:建立新 thread执行类别中的函数 4:建立新 thread 执行 la...
    99+
    2023-01-08
    C++ std::thread线程 C++ std::thread
  • Java多线程Thread类的使用详解
    目录1.创建一个线程2.start()方法与run()方法3.查看线程4.创建线程的各种方法4.1实现Runnable接口4.2使用匿名内部类4.3使用匿名内部类实现Runnable...
    99+
    2022-12-03
    Java多线程Thread Java Thread Java多线程
  • C++ 多线程之互斥量(mutex)详解
    目录std::mutexstd::recursive_mutexstd::time_mutexstd::recursive_timed_mutexstd::shared_mutexs...
    99+
    2022-11-13
  • C#多线程学习之Thread、ThreadPool、Task、Parallel四者区别
    目录ThreadThreadPoolTaskParallelTask专讲线程(英语:thread)是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一...
    99+
    2022-11-12
  • Java Thread之Sleep()案例详解
    一、API简介 Thread.sleep()是Thread类的一个静态方法,使当前线程休眠,进入阻塞状态(暂停执行),如果线程在睡眠状态被中断,将会抛出IterruptedExcep...
    99+
    2022-11-12
  • Java多线程之Worker Thread模式
    目录一.Worker Thread模式二   .Worker Thread模式中的角色1.Client(委托者)2.Channel(通信线路)3.Worker(工...
    99+
    2022-11-12
  • Ruby多线程库(Thread)使用方法详解
    Thread是Ruby的线程库,Thread库已经内置在Ruby中,但如果想要使用线程安全的Queue、Mutex以及条件变量等,则需要手动require 'thread&#...
    99+
    2022-11-13
  • C#多线程之任务的用法详解
    目录一.启动任务1.使用线程池的任务2.同步任务3.使用单独线程的任务二.任务的结果————Future三.连续的任务四.任务的层次结...
    99+
    2022-11-13
  • C++中std::thread线程怎么使用
    本篇内容主要讲解“C++中std::thread线程怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++中std::thread线程怎么使用”吧!1:std::thread的基本用法最简...
    99+
    2023-07-04
  • C++11学习之多线程的支持详解
    目录C++11中的多线程的支持1.C++11中的原子类型1.1 原子类型的接口1.2简单自旋锁的实现2.提高并行程度2.1 memory_order的参数2.2 release-ac...
    99+
    2023-02-06
    C++11多线程支持 C++11多线程
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作