C++线程之thread详解

目录
  • 1.创建线程
  • 2.守护线程
  • 3.可调用对象
  • 4.传参
  • 5.线程的移动和复制
  • 6.线程id
  • 7.互斥mutex
  • 总结

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

总结

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

(0)

相关推荐

  • C++实现CreatThread函数主线程与工作线程交互的方法

    本文实例讲述了C++开启线程CreatThread函数的使用,实现主线程与工作线程交互的功能.分享给大家供大家参考. 具体实现代码如下: 复制代码 代码如下: //线程函数  DWORD WINAPI ThreadProc(LPVOID lpParameter)  {      for (int i=0;i<20;i++)      {          printf("I'm in thread,count=%d\n",i);      }      return 0;  } 

  • C/C++ Qt QThread线程组件的具体使用

    QThread库是QT中提供的跨平台多线程实现方案,使用时需要继承QThread这个基类,并重写实现内部的Run方法,由于该库是基本库,默认依赖于QtCore.dll这个基础模块,在使用时无需引入其他模块. 实现简单多线程 QThread库提供了跨平台的多线程管理方案,通常一个QThread对象管理一个线程,在使用是需要从QThread类继承并重写内部的Run方法,并在Run方法内部实现多线程代码. #include <QCoreApplication> #include <iostre

  • C++11 thread多线程编程创建方式

    目录 1 线程创建与结束 线程的创建方式: 线程的结束方式: 2 互斥锁 <mutex> 头文件介绍 std::mutex 介绍 std::mutex 的成员函数 std::lock_guard std::unique_lock 示例: 原子变量 线程同步通信 线程死锁 1 线程创建与结束 C++11 新标准中引入了四个头文件来支持多线程编程,他们分别是<atomic> ,<thread>,<mutex>,<condition_variable>

  • C++11并发编程:多线程std::thread

    一:概述 C++11引入了thread类,大大降低了多线程使用的复杂度,原先使用多线程只能用系统的API,无法解决跨平台问题,一套代码平台移植,对应多线程代码也必须要修改.现在在C++11中只需使用语言层面的thread可以解决这个问题. 所需头文件<thread> 二:构造函数 1.默认构造函数 thread() noexcept 一个空的std::thread执行对象 2.初始化构造函数 template<class Fn, class... Args> explicit th

  • C++线程之thread详解

    目录 1.创建线程 2.守护线程 3.可调用对象 4.传参 5.线程的移动和复制 6.线程id 7.互斥mutex 总结 1.创建线程 直接初始话thread类对象进行创建线程,创建线程后调用join()方法,让主线程等待子线程完成工程. #include <iostream> #include <thread> void thread_function() { std::cout << "thread function\n"; } int main

  • Python线程编程之Thread详解

    目录 一.线程编程(Thread) 1.线程基本概念 1.1.什么事线程 1.2.线程特征 二.threading模块创建线程 1.创建线程对象 2. 启动线程 3. 回收线程 4.代码演示 5.线程对象属性 6.自定义线程类 7.一个很重要的练习 我很多不懂 8.线程间通信 1. 线程Event 代码演示 2. 线程锁 Lock代码演示 10.死锁及其处理 1.定义 2.图解 3. 死锁产生条件 4.死锁代码演示 python线程GIL 1.python线程的GIL问题 (全局解释器锁) 总结

  • Java并发编程之ThreadLocal详解

    目录 一.什么是ThreadLocal? 二.ThreadLocal的使用场景 三.如何使用ThreadLocal 四.数据库连接时的使用 五.ThreadLocal工作原理 六.小结 七.注意点 一.什么是ThreadLocal? ThreadLocal叫做线程本地变量,ThreadLocal中填充的变量属于当前线程,该变量对其他线程而言是隔离的.ThreadLocal为变量在每个线程中都创建了一个副本,则每个线程都可以访问自己内部的副本变量. 二.ThreadLocal的使用场景 1.当对象

  • python 编程之twisted详解及简单实例

    python 编程之twisted详解 前言: 我不擅长写socket代码.一是用c写起来比较麻烦,二是自己平时也没有这方面的需求.等到自己真正想了解的时候,才发现自己在这方面确实有需要改进的地方.最近由于项目的原因需要写一些Python代码,才发现在python下面开发socket是一件多么爽的事情. 对于大多数socket来说,用户其实只要关注三个事件就可以了.这分别是创建.删除.和收发数据.python中的twisted库正好可以帮助我们完成这么一个目标,实用起来也不麻烦.下面的代码来自t

  • C#多线程之Thread中Thread.Join()函数用法分析

    本文实例讲述了C#多线程之Thread中Thread.Join()函数用法.分享给大家供大家参考.具体分析如下: Thread.Join()在MSDN中的解释:Blocks the calling thread until a thread terminates 当NewThread调用Join方法的时候,MainThread就被停止执行, 直到NewThread线程执行完毕. Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));

  • java并发编程之cas详解

    CAS(Compare and swap)比较和替换是设计并发算法时用到的一种技术.简单来说,比较和替换是使用一个期望值和一个变量的当前值进行比较,如果当前变量的值与我们期望的值相等,就使用一个新值替换当前变量的值.这听起来可能有一点复杂但是实际上你理解之后发现很简单,接下来,让我们跟深入的了解一下这项技术. CAS的使用场景 在程序和算法中一个经常出现的模式就是"check and act"模式.先检查后操作模式发生在代码中首先检查一个变量的值,然后再基于这个值做一些操作.下面是一个

  • C#多线程之Thread中Thread.IsAlive属性用法分析

    本文实例讲述了C#多线程之Thread中Thread.IsAlive属性用法.分享给大家供大家参考.具体如下: Thread.IsAlive属性 ,表示该线程当前是否为可用状态 如果线程已经启动,并且当前没有任何异常的话,则是true,否则为false Start()后,线程不一定能马上启动起来,也许CPU正在忙其他的事情,但迟早是会启动起来的! Thread oThread = new Thread(new ThreadStart(Back.Start)); oThread.Start();

  • 对python pandas 画移动平均线的方法详解

    数据文件 66001_.txt 内容格式: date,jz0,jz1,jz2,jz3,jz4,jz5 2012-12-28,0.9326,0.8835,1.0289,1.0027,1.1067,1.0023 2012-12-31,0.9435,0.8945,1.0435,1.0031,1.1229,1.0027 2013-01-04,0.9403,0.8898,1.0385,1.0032,1.1183,1.0030 ... ... pd_roll_mean1.py # -*- coding: u

  • Python数字图像处理之霍夫线变换实现详解

    在图片处理中,霍夫变换主要是用来检测图片中的几何形状,包括直线.圆.椭圆等. 在skimage中,霍夫变换是放在tranform模块内,本篇主要讲解霍夫线变换. 对于平面中的一条直线,在笛卡尔坐标系中,可用y=mx+b来表示,其中m为斜率,b为截距.但是如果直线是一条垂直线,则m为无穷大,所有通常我们在另一坐标系中表示直线,即极坐标系下的r=xcos(theta)+ysin(theta).即可用(r,theta)来表示一条直线.其中r为该直线到原点的距离,theta为该直线的垂线与x轴的夹角.如

  • C#多线程之Thread类详解

    使用System.Threading.Thread类可以创建和控制线程. 常用的构造函数有: // 摘要: // 初始化 System.Threading.Thread 类的新实例,指定允许对象在线程启动时传递给线程的委托. // // 参数: // start: // System.Threading.ParameterizedThreadStart 委托,它表示此线程开始执行时要调用的方法. // // 异常: // System.ArgumentNullException: // star

随机推荐