请避免直接使用Thread

第二十六篇:线程池与直接使用Thread的区别 有显著区别,线程池的实现方式、性能特点以及与C#线程池的差异也值得探讨。在C++中,使用线程池和直接使用。 阅读详情

XiongWanPing 2018.04.12

BaseLooper是一个跨平台的c++通用框架,支持网络非阻塞异步通讯,多线程组件消息处理,支持服务器,设备端和客户端开发,支持Android,ios, linux, OSX和Windows等操作系统,支持嵌入式设备,只要目标系统支持c++11编译器,就可轻松移植

 

本文档是为了引出BaseLooper框架做下铺垫,先提出问题,后面会给出解决办法。

Linux(包括linux,android,osx,ios)和Windows都提供了线程函数,但其粒度太大,比如pthread_create,只是把线程创建并跑起来,然后就没有更细致的操作接口了,使用起来是不太方便的。很多线程中运行过程中都需要和其他线程或组件进行通讯,对这个常见的需求,Thread类接口没有直接提供有效的办法。

 

大多数ThreadEntry的简要实现如下

ThreadEntry(..)

{

                while(!stop)

{

                …

}

}

这种做法简单,但缺少统一规划,代码看起来也不优雅。

如果程序中需要大量的辅助线程,则每个线程的代码实现都不尽相同。可能充满令人疑惑的加锁代码

 

未完待续

 

 


C#中Task与Thread的区别 摘要: C#中的Task和Thread是多线程编程的核心机制,但存在显著差异。Thread直接对应操作系统线程,资源占用高,适合长时间运行任务;Task基于线程池管理,资源利用率高,支持异步编程(async/await)、返回值、异常处理和任务组合,适合短时任务和复杂并发逻辑。Thread提供精细控制(如优先级),但缺乏原生取消支持;Task则集成CancellationToken等现代特性,代码可维护性更强。开发中优先推荐Task,仅在需要长期运行或底层控制时使用Thread。 阅读详情

相关推荐

C++11 std::thread的使用注意事项

文章目录A. `std::thread`不可复制B. `std::thread`在栈内创建后,需要在同一个作用域内调用`join()` 或者 `detach()`, 否则退出作用域后,程序会异常退出, 具体原因如下:C. 调用new 创建的std::thread, 禁止直接使用delete, 需要在调用delete之前,调用 join()或者 detach() A. std::thread不可复制 比如以下代码: void task1(); //具体实现这里忽略 int main(int argc, cha

二进制君 2万+

JAVA线程误区:Thread不能随便使用

  工作原因,需要找出程序中内存泄漏的地方(泄漏现象:JAVA进程的内存,一直在缓慢的增长,到最后出现OutOfMemory),当然市场上有很多的这样剖析工具了象Jprobe等,但是因为商业原因,没能采用:(.   于是就用java本身的-Xrunhprof参数+HPjmeter,进行剖析,经过跟踪分析,发现有大量的Thread一直是活动对象,及时run()已经执行过!类似代码如下:     V...

lovec的专栏 259

开源CMDB与资产管理平台对比报告

本文对比分析了9款主流开源CMDB平台,从集成能力、功能完整性和多语言支持三个维度进行评测。重点介绍了VeCMDB、蓝鲸CMDB、WeCMDB和OpsAny等国产平台的特色:VeCMDB以动态模型和自动发现见长;蓝鲸CMDB适合超大规模企业级应用;WeCMDB专注金融级高并发场景;OpsAny提供一体化运维解决方案。针对不同规模企业给出选型建议:中小团队推荐Snipe-IT等轻量工具;大型企业建议蓝鲸或WeCMDB;需国产化适配的可选VeCMDB或OpsAny。文章还特别指出iTop、GLPI等适合ITIL

huang0612123的博客 1080

使用 Thread

多线程直接使用 Thread继承 Thread实现 Runnable,通过 Thread 调用实现 Callable,通过 Thread 调用线程的状态线程状态的定义和位置获取状态的方法线程状态及处于该状态的场景Thread 的常用方法封装使用 Thread 直接使用 Thread 继承 Thread new Thread(){ @Override public void run() { super.run();

qq1302526289的博客 484

一本集成电路静态时序设计经典之作(可下载)

本书全面深入探讨集成电路设计中关键技术的专著,涵盖了从基础知识到高级应用的各个方面。本书详细介绍了集成电路的发展历程、**静态时序分析的重要性、基本时序模型、时序信息库文件的构建、时序约束的设置、串扰噪声的影响及其控制方法**,并通过实战案例展示了如何进行有效的时序分析和优化。

nuoweishizi的博客 850

一文入门Qwen-Agent【附实战代码】

Qwen-Agent 是一个开源框架,用于开发基于 Qwen 模型的 AI 智能体应用,一文带你入门使用

m0_55303420的博客 1873

Java直接调用Thread类中的run()方法

//线程直接调用run()和调用start()后再调用run()的不同 public class Test05 { public static void main(String[] args) { Thread t=new Thread(){ public void run(){ pong(); } }; //t.start();//开启一个新线程,会调用该线程

lislcliu的博客 5620

MySQL根据idb文件恢复数据

恢复前提 MySQL 5.* 和 8.* 的恢复方式大同小异,最基本的区别是8.* 中,不再有表结构frm文件,所以要恢复 8.* 的数据,就必须要有完整的建表语句。 而恢复 5.* 的数据,就需要idb文件和 frm文件,当然,如果有完整的建表语句的话,不用frm文件也行。 恢复步骤 需要注意的是,以下操作需要选定数据库后执行。 5.* 恢复表结构 确定表列数 首先创建一张 与需要恢复数据的表 的名字相同的新表,如果已知原表的字段数量的话,就按照原表字段数建表,字段名和类型都不用考虑,如果不知道数量的话,

weixin_45121446的博客 5447

java线程直接调用run_直接调用线程的run方法是否可以启动线程?

首先Thread类中run()和start()方法的区别如下:run()方法:在本线程内调用该Runnable对象的run()方法,可以重复多次调用;start()方法:启动一个线程,调用该Runnable对象的run()方法,不能多次启动一个线程;public class Test implements Runnable{public static void main(String[] args...

weixin_42510053的博客 2956

学习使用turtlebot2——ROS上安装turtlebot2

安装环境:    安装Ubuntu 14.04版本和ROS Indigo    参考:http://wiki.ros.org/turtlebot/Tutorials安装步骤    有两种安装方法,一种直接的安装命令,另外一种源码编译安装,区别在于:直接安装命令是安装在电脑默认路径/opt/ros/indigo/share里面不便于更改代码,因为默认路径下文件一般有访问权限,无法直接更改,需要使用s...

weixin_42670641的博客 2531

vscode配置matlab工作环境

前面有两篇文章我们分别讲了在vscode里面如何配置C语言环境和python环境,那两篇文章总体来说比较复杂,当然这篇也有许多有趣的问题。 附上链接: 文章目录matlab简介基本要求code runner插件与matlab相关的插件添加路径小结code runner是否支持更多语言更多选择另一个选择 matlab简介 MATLAB是美国MathWorks公司出品的商业数学软件,用于数据分析、无线通信、深度学习、图像处理与计算机视觉、信号处理、量化金融与风险管理、机器人,控制系统等领域。 MATLAB是ma

Cachel Wood的博客 4540

异步多线程之Thread详解

异步多线程版本 在 .NET中随着时间的发展,线程是有许多个版本的1.0 Thread、2.0TthreadPool、3.0 Task、4.0 Parallel 等,今天我就一一进行讲解。 1.0 时代 在1.0 时代C# 就考虑到了多线程,于是就设计了 Thread 其实现在都不会再用了,除非在维护老的项目已经用了的。Thread 也是比较鸡肋的,有很多缺陷,但也并不是一无是处。 首先看 Thread 的构造函数,ThreadStart 无参数类型的委托、ParameterizedThreadStart

菜鸟厚非 9474

OPTEE v4.4.0 qemu_v8环境搭建(支持Hafnium)

一、前提条件 二、拉取代码 三、下载工具链 四、修改代码 五、编译 六、运行

AI-安全-功耗 889

【C#】Thread.Join()、异步等待和直接join

Thread.Join()、异步等待和直接join

weixin_44939430的博客 1711

解锁RK平台黑科技:DPDK加速与硬件卸载实战

本文探讨了在RK平台上通过DPDK加速与硬件卸载技术构建高性能网络架构的方法。RK平台凭借强大的硬件性能为高并发网络处理提供基础,而DPDK通过用户态驱动、轮询机制等技术绕过内核瓶颈,显著提升数据包处理效率。硬件卸载则将校验和计算等任务交由专用硬件,释放CPU资源。实践案例显示,该方案可使网络吞吐量提升至理论极限,延迟降至5ms以下,CPU利用率降低40%。文章详细介绍了配置步骤、优化方法和常见问题解决方案,并展望了该技术在5G、车联网等新兴领域的应用前景。

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 1279

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

双冒号写法可以直接放进Thread()里的原因

我是一个从汽车行业转行IT的项目经理,我是Edward。今天学volatile的时候发现了一个奇怪的现象,为什么会有对象直接双冒号接方法的写法? 为什么还可以直接放到Thread()里? 要知道没有继承Runnable接口对象的方法是不能直接放到Thread()里的哟。小朋友你是否有很多问号? 先放上这段令人以后的代码: package com.mashibing.juc.c_012_volati...

Forever Young 971

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

c#中使用Thread

这里说说Thread,之前的文章中有BackgroundWorker的用法。他们都是线程,每一个用法在不同的场景不同。 1.首先看界面,启动2个线程,一个进行加法计算,一个进行减法计算。并且使界面不卡,随时可以拖动 2.在load方法中新建2个线程 3. 两个线程分别运行加法的方法A和减法的方法B 注意:这里需要使用Invoke,否则报错下图 4.效果如下 using System; using System.Collections.Generic; using System.

故里2130 8171

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

使用STM32CubeMX生成rt thread工程

使用STM32CubeMX生成rt_tread工程

记忆中的美丽瞬间 1万+

thread导致的内存泄漏实例——为什么使用静态内部类避免内存泄漏

背景:有个数据库处理类,包含一个thread负责对数据库进行写入(耗时操作)。该thread在某个fragment中会被重新初始化并开始。 private void updateBookShelf() { Globals.getInstance().setBookShelves(bookShelves); if (Globa...

SylG17的博客 1047

C++11 thread 参数传递深度解析:为什么需要 std::ref 而非直接引用?

摘要:C++11的std::thread在参数传递时默认采用值拷贝方式,即使线程函数声明为引用参数。这种设计避免了多线程中的悬空引用问题,但也导致无法通过引用修改原始变量或传递不可拷贝对象。std::ref/cref提供解决方案,它们包装引用使其按引用传递,同时在语法上明确标识出潜在的共享数据。本文通过代码示例展示了直接传递引用的陷阱,并解释std::ref如何保留引用语义,同时提醒开发者注意线程安全。

Lion_Long的博客 1914

Runnable和Thread比较

Runnable和Thread比较 1、 Runnable更容易实现资源共享,能多个线程同时处理一个资源。 //使用Thread实现售票功能 public static void main(String[] args) { new MyThread().start(); new MyThread().start(); } class MyThread ex...

柳絮 3005

c++ thread 使用不当导致的崩溃问题

看个例子 1 class CTimer{ 2 public: 3 // 析构函数 4 virtual ~CTimer(){ 5 6 } 7 // 开始 8 void start() 9 { 10 b_exit = false; 11 i = 10; 12 ...

weixin_34161064的博客 1183

Java thread 怎么用_Java Thread 的使用

写俄罗斯方块游戏的时候用线程遇到一点问题。如果一个类继承Thread,则不适合资源共享。但是如果实现了Runable接口的话,则很容易的实现资源共享。实现Runnable接口比继承Thread类所具有的优势:1):适合多个相同的程序代码的线程去处理同一个资源2):可以避免java中的单继承的限制3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立(附)start 和 run 方法解释:1...

weixin_34632164的博客 645

Thread类的介绍

本文介绍了Java中线程的基本概念和创建方式。线程是操作系统中的执行流,Java通过Thread类封装了线程操作。文章详细讲解了6种创建线程的方法:继承Thread类、实现Runnable接口、匿名内部类、Lambda表达式、Callable接口与FutureTask、线程池(Executor框架)。同时阐述了Thread类的常用方法,包括start()启动线程、interrupt()中断线程、join()等待线程、sleep()休眠线程等。文章还分析了线程的状态转换(NEW、TERMINATED、RUNN

2302_80826557的博客 1139

Multi-thread--C++11中<thread>的使用

C++11中加入了<thread>头文件,此头文件主要声明了std::thread线程类。C++11的标准类std::thread对线程进行了封装。std::thread代表了一个线程对象。应用C++11中的std::thread便于多线程程序的移值。 <thread>是C++标准程序库中的一个头文件,定义了C++11标准中的一些表示线程的类、用于互斥访问的类与方法等。 类...

Jensen Lee的博客 1052
上一篇: lua的一个坑:和.的区别
下一篇: 请避免直接使用new和delete
xwpcom
博客等级 码龄24年 16粉丝 60原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值