【Linux学习笔记49】线程池机制

linux操作系统常用面试题目 1、请描述一下用多线程怎么实现生产者消费者模型 2、知道nginx的惊群现象吗?怎么解决? 3、请说一下epoll的内核实现,都涉及哪些数据结构? 4、select和epoll的区别? 5、fork()都会做哪些复制? 6、什么是写时拷贝?Fork以后,父进程打开的文件指针位置在子进程里面是否一样? 7、你项目中为什么使用进程池?而不是用线程池?不同场景怎么选择请列举一些例子! 8、tcp/ip的... 阅读详情

引言

线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。如果一个程序任务比较多,那么我们可以使用多线程来分担任务,但是并不是线程越多越好,虽然创建的线程被称为轻量级线程,但也占用资源。因此,需要线程池机制来维持整个程序的进行。

线程池机制
  1. 在一开始的时候,创建若干条线程,然后使其处于睡眠状态等待任务。
  2. 主线程接收任务,然后唤醒线程,并然其承担任务。
  3. 如果线程池中的线程数目不够,可以继续增加线程。如果线程数目太多,可以减少线程。
  4. 使用线程池保证进程中的线程数量处于一个恰当的数目。

线程池的原理

在这里插入图片描述

  • 首先创建若干条线程,如图TID1,TID2,TID3
  • 主线程领取任务,并且投放任务,使用链表将它们连接起来
  • 主线程唤醒线程去领取
  • 线程取得任务后并且执行任务

代码实现

main.c:

#include "thread_pool.h"

void *mytask(void *arg)
{
	int n = (int)arg;

	printf("[%u][%s] ==> job will be done in %d sec...\n",
		(unsigned)pthread_self(), __FUNCTION__, n);

	sleep(n);

	printf("[%u][%s] ==> job done!\n",
		(unsigned)pthread_self(), __FUNCTION__);

	return NULL;
}

void *count_time(void *arg)
{
	int i = 0;
	while(1)
	{
		sleep(1);
		printf("sec: %d\n", ++i);
	}
}

int main(void)
{
	pthread_t a;
	pthread_create(&a, NULL, count_time, NULL);

	// 1, initialize the pool
	thread_pool *pool = malloc(sizeof(thread_pool));
	init_pool(pool, 2);

	// 2, throw tasks
	printf("throwing 3 tasks...\n");
	add_task(pool, mytask, (void *)(rand()%10));
	add_task(pool, mytask, (void *)(rand()%10));
	add_task(pool, mytask, (void *)(rand()%10));

	// 3, check active threads number
	printf("current thread number: %d\n",
			remove_thread(pool, 0));
	sleep(9);

	// 4, throw tasks
	printf("throwing another 2 tasks...\n");
	add_task(pool, mytask, (void *)(rand()%10));
	add_task(pool, mytask, (void *)(rand()%10));

	// 5, add threads
	add_thread(pool, 2);

	sleep(5);

	// 6, remove threads
	printf("remove 3 threads from the pool, "
	       "current thread number: %d\n",
			remove_thread(pool, 3));

	// 7, destroy the pool
	destroy_pool(pool);
	return 0;
}

thread_pool.c

#include "thread_pool.h"

void handler(void *arg)
{
	printf("[%u] is ended.\n",
		(unsigned)pthread_self());

	pthread_mutex_unlock((pthread_mutex_t *)arg);
}

void *routine(void *arg)
{
	#ifdef DEBUG
	printf("[%u] is started.\n",
		(unsigned)pthread_self());
	#endif

	thread_pool *pool = (thread_pool *)arg;
	struct task *p;

	while(1)
	{
		
		pthread_cleanup_push(handler, (void *)&pool->lock);
		pthread_mutex_lock(&pool->lock);
	
		// 1, no task, and is NOT shutting down, then wait
		while(pool->waiting_tasks == 0 && !pool->shutdown)
		{
			pthread_cond_wait(&pool->cond, &pool->lock);
		}

		// 2, no task, and is shutting down, then exit
		if(pool->waiting_tasks == 0 && pool->shutdown == true)
		{
			pthread_mutex_unlock(&pool->lock);
			pthread_exit(NULL); // CANNOT use 'break';
		}

		// 3, have some task, then consume it
		p = pool->task_list->next;
		pool->task_list->next = p->next;
		pool->waiting_tasks--;

		//================================================//
		pthread_mutex_unlock(&pool->lock);
		pthread_cleanup_pop(0);
		//================================================//

		pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
		(p->do_task)(p->arg);
		pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

		free(p);
	}

	pthread_exit(NULL);
}

bool init_pool(thread_pool *pool, unsigned int threads_number)
{
	pthread_mutex_init(&pool->lock, NULL);
	pthread_cond_init(&pool->cond, NULL);

	pool->shutdown = false;
	pool->task_list = malloc(sizeof(struct task));
	pool->tids = malloc(sizeof(pthread_t) * MAX_ACTIVE_THREADS);

	if(pool->task_list == NULL || pool->tids == NULL)
	{
		perror("allocate memory error");
		return false;
	}

	pool->task_list->next = NULL;

	pool->max_waiting_tasks = MAX_WAITING_TASKS;
	pool->waiting_tasks = 0;
	pool->active_threads = threads_number;

	int i;
	for(i=0; i<pool->active_threads; i++)
	{
		if(pthread_create(&((pool->tids)[i]), NULL,
					routine, (void *)pool) != 0)
		{
			perror("create threads error");
			return false;
		}

		#ifdef DEBUG
		printf("[%u]:[%s] ==> tids[%d]: [%u] is created.\n",
			(unsigned)pthread_self(), __FUNCTION__,
			i, (unsigned)pool->tids[i]);
		#endif
	}

	return true;
}

bool add_task(thread_pool *pool,
	      void *(*do_task)(void *arg), void *arg)
{
	struct task *new_task = malloc(sizeof(struct task));
	if(new_task == NULL)
	{
		perror("allocate memory error");
		return false;
	}
	new_task->do_task = do_task;
	new_task->arg = arg;
	new_task->next = NULL;

	//============ LOCK =============//
	pthread_mutex_lock(&pool->lock);
	//===============================//

	if(pool->waiting_tasks >= MAX_WAITING_TASKS)
	{
		pthread_mutex_unlock(&pool->lock);

		fprintf(stderr, "too many tasks.\n");
		free(new_task);

		return false;
	}
	
	struct task *tmp = pool->task_list;
	while(tmp->next != NULL)
		tmp = tmp->next;

	tmp->next = new_task;
	pool->waiting_tasks++;

	//=========== UNLOCK ============//
	pthread_mutex_unlock(&pool->lock);
	//===============================//

	#ifdef DEBUG
	printf("[%u][%s] ==> a new task has been added.\n",
		(unsigned)pthread_self(), __FUNCTION__);
	#endif

	pthread_cond_signal(&pool->cond);
	return true;
}

int add_thread(thread_pool *pool, unsigned additional_threads)
{
	if(additional_threads == 0)
		return 0;

	unsigned total_threads =
			pool->active_threads + additional_threads;

	int i, actual_increment = 0;
	for(i = pool->active_threads;
	    i < total_threads && i < MAX_ACTIVE_THREADS;
	    i++)
	{
		if(pthread_create(&((pool->tids)[i]),
					NULL, routine, (void *)pool) != 0)
		{
			perror("add threads error");

			// no threads has been created, return fail
			if(actual_increment == 0)
				return -1;

			break;
		}
		actual_increment++; 

		#ifdef DEBUG
		printf("[%u]:[%s] ==> tids[%d]: [%u] is created.\n",
			(unsigned)pthread_self(), __FUNCTION__,
			i, (unsigned)pool->tids[i]);
		#endif
	}

	pool->active_threads += actual_increment;
	return actual_increment;
}

int remove_thread(thread_pool *pool, unsigned int removing_threads)
{
	if(removing_threads == 0)
		return pool->active_threads;

	int remaining_threads = pool->active_threads - removing_threads;
	remaining_threads = remaining_threads > 0 ? remaining_threads : 1;

	int i;
	for(i=pool->active_threads-1; i>remaining_threads-1; i--)
	{
		errno = pthread_cancel(pool->tids[i]);

		if(errno != 0)
			break;

		#ifdef DEBUG
		printf("[%u]:[%s] ==> cancelling tids[%d]: [%u]...\n",
			(unsigned)pthread_self(), __FUNCTION__,
			i, (unsigned)pool->tids[i]);
		#endif
	}

	if(i == pool->active_threads-1)
		return -1;
	else
	{
		pool->active_threads = i+1;
		return i+1;
	}
}

bool destroy_pool(thread_pool *pool)
{
	// 1, activate all threads
	pool->shutdown = true;
	pthread_cond_broadcast(&pool->cond);

	// 2, wait for their exiting
	int i;
	for(i=0; i<pool->active_threads; i++)
	{
		errno = pthread_join(pool->tids[i], NULL);
		if(errno != 0)
		{
			printf("join tids[%d] error: %s\n",
					i, strerror(errno));
		}
		else
			printf("[%u] is joined\n", (unsigned)pool->tids[i]);
		
	}

	// 3, free memories
	free(pool->task_list);
	free(pool->tids);
	free(pool);

	return true;
}

thread_pool.h:

#ifndef _THREAD_POOL_H_
#define _THREAD_POOL_H_

#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include <errno.h>
#include <pthread.h>

#define MAX_WAITING_TASKS	1000
#define MAX_ACTIVE_THREADS	20

struct task
{
	void *(*do_task)(void *arg);
	void *arg;

	struct task *next;
};

typedef struct thread_pool
{
	pthread_mutex_t lock;
	pthread_cond_t  cond;

	bool shutdown;

	struct task *task_list;

	pthread_t *tids;

	unsigned max_waiting_tasks;
	unsigned waiting_tasks;
	unsigned active_threads;
}thread_pool;


bool init_pool(thread_pool *pool, unsigned int threads_number); //初始化线程
bool add_task(thread_pool *pool, void *(*do_task)(void *arg), void *task); //增加任务
int  add_thread(thread_pool *pool, unsigned int additional_threads_number); //增加线程
int  remove_thread(thread_pool *pool, unsigned int removing_threads_number);//移除线程
bool destroy_pool(thread_pool *pool);  //销毁线程

void *routine(void *arg);


#endif

程序运行结果:

在这里插入图片描述
在这里插入图片描述

黑马linux网络编程 1、协议 2、分层模型结构 3、c/s模型:client-server 4、b/s模型:browser-server 5、网络传输流程: 6、以太网帧协议: 7、IP协议 8、UDP 9、IP协议: 10、网络套接字 socket 11、网络字节序 12、IP地址转换函数 13、sockaddr地址结构 14、网络套接字函数 15、TCP通信流程分析 16、三次握手协议 17、四次挥手 18、滑动窗口 19、错误处理函数: 阅读详情

相关推荐

Unity3D用c#脚本调用前端javascript函数:H5获取unity - webgl 加载并初始化完成的消息

unity3d发布的Webgl 可以作为静态文件加载到H5页面中,并通过javascript 调用unity内置的C#脚本函数,详见Webgl调用unity api。而往往我们需要知道Webgl ready的消息,本文将给出unity 内部调用javascript函数的方案加以解决。

Bravo 2476

一文彻底搞懂线程池—ThreadPoolExecutor

首先是设置线程池状态为STOP,前面的代码我们可以看到,是对SHUTDOWN有一些额外的判断逻辑,但是对于>=STOP,基本都是reject,STOP也是比SHUTDOWN更加严格的一种状态。所以,我们有没有一个好的方案能做到线程的复用呢?我个人认为,如果想了解明白线程池,那么就一定要理解好各个状态之间的转换,想理解转换,线程池的终止机制是很好的一个途径。注释说的很清楚,为了能及时的中断此Worker,因为线程存在未Start的情况,此时是不能响应中断的,如果此时status变为STOP,则不能中断线程。

lvyuanj的专栏 1234

labview的TDMS文件读写

本文先介绍TDMS概念和文件结构,然后介绍VI如何使用,最后分析一个labview的自带范例

观则明的博客 1万+

深入理解线程池(详解)

线程池做的工作主要是控制运行的线程的数量,处理过程中将任务放入队列,然后在线程创建后启动这些任务,如果线程数量超过了最大数量超出数量的线程排队等候,等其它线程执行完毕,再从队列中取出任务来执行。他的主要特点为:线程复用;控制最大并发数;管理线程。

weixin_44825912的博客 1万+

LVGL高效加载外部Flash图片资源的实现与优化

本文深入探讨了在嵌入式UI开发中,如何为LVGL高效加载外部Flash中的图片资源。针对内部Flash容量不足的痛点,详细解析了LVGL的图片处理原理,并对比了内存映射与流式解码两种主流实现方案。文章重点提供了性能优化技巧与实战避坑指南,旨在帮助开发者实现流畅的图片加载体验,解决SPI Flash读取慢、内存占用高等核心挑战。

t1u2v的博客 462

关于图像傅里叶变换得到的频谱图的通俗理解

傅里叶变换过程: 经过傅里叶变化且频谱居中化处理的频谱图: 1.如果将图像某一行上的灰度变化看作是一个离散信号,那么整张图像可以看作是一个分布在二维平面上的信号,因此图像可看作是空间域信号。傅里叶变换则是将图像灰度分布(空间域信号)变换到了频域上,给我们提供了观察图像的另一个视角。 2.图像的频谱图(频谱居中后)的中心点是频率最低点,以该点为圆心,不同半径的上的点表示不同的频率。这里的图像频率是指对应原图像中的某灰度曲线变化的快慢(这么说不严谨,但是按照上面第1点的角度,似乎也可以这么理解

daimashiren的博客 2万+

详述Java线程池实现原理

线程池是什么 线程池就是创建若干个可执行的线程放入一个池(容器)中,有任务需要处理时,会提交到线程池中的任务队列,处理完之后线程并不会被销毁,而是仍然在线程池中等待下一个任务。 使用线程池有什么好处 降低资源消耗:通过重复利用现有的线程来执行任务,避免多次创建和销毁线程 提高响应速度:因为省去了创建线程这个步骤,所以在拿到任务时,可以立刻开始执行 提供附加功能:线程池的可拓展性使得我们可以自己加入新的功能,比如说定时、延时来执行某些线程 提高线程的可管理性:线程是稀缺资源,如果无限制的创建,不仅会消耗系统

养歌的博客 3071

移花接木,玩转CANoe的几种扩展接口应用(五)——串口设备

近期看到粉丝朋友在CANoe自动化测试方面的关注度很大,今天就围绕这个做一个专题,总结一下以往项目上用过的几种CANoe扩展接口,分享出来希望对相关领域的网友有所帮助。本文是该专题的第五篇文章,主要讲解了串口设备的功能配置、连接方法、配置方法、调用方法,最后分析了这种扩展借口应用的特点和适用场景。

Mr.Cssust的博客 2369

线程池的创建&&工作机制

如果是在Java中,可以使用JUC并发编程包中的ThreadPoolExecutor来实现非常灵活地自定义线程池。 ### 线程池的参数含义 int corePoolSize(核心线程数):正常情况下,系统应该能同时工作的线程数(随时就绪状态)int maximumPoolSize(最大线程数):极限情况下,线程池可容纳的最多线程long keepAliveTime(空闲线程存活时间):非核心线程在没有任务的情况下,过多久要删除,释放无用的资源

m0_59084856的博客 1343

Python在Genesis2000 CAM软件中的编程应用

Genesis2000是一款功能强大的计算机辅助制造(CAM)软件,它提供了广泛的功能和工具,用于帮助制造商进行CAD(计算机辅助设计)到CAM的转换。在Genesis2000中,我们可以利用Python的灵活性和功能来扩展软件的自定义能力,并通过编写脚本来自动化各种制造任务。例如,假设我们需要在Genesis2000中添加一个新的操作,用于自动计算零部件的重量。我们可以编写一个Python脚本,通过遍历模型的几何数据并应用相关的计算公式,来实现这个功能。

PixelEnigma的博客 2424

【PointNet++】使用Open3D对分割后的结果可视化

PointNet++中的局部分割网络预测后是没有可视化文件的,所以需要自己通过编写Open3D或者PCL点云算法去可视化,在本人经过查找翻阅修改后,实现了网络输出点云分割后结果的可视化。已实现推测单个点云,并可视化。

纵马踏花向自由 2455

线程池核心原理分析-即将作废

一、基础概念 线程池是一种多线程的处理方式,线程池可以方便得对线程进行创建,销毁和管理。 线程池解决的问题: 1.线程池未出现前:如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间,而且会消耗系统资源。 如果使用线程池:线程在run()方法执行完后,不用将其销毁,让它继续保持空闲状态,当有新任务...

sinat_34814635的博客 3035

Android性能分析——GPU资源耗尽分析(二十六)

本文分析了Android车机系统中GPU资源耗尽导致应用闪退的案例。通过日志定位到EGL_BAD_ALLOC错误,表明系统无法分配足够图形资源创建EGL上下文。问题主要发生在渲染线程初始化EGL环境时,根源在于车机系统对GPU资源的严格限制(如EGLContext数量、GPU内存等)。文中详细解读了SkiaOpenGLPipeline和EglManager的源码调用链路,指出createContext()函数中的致命断言是崩溃的直接原因,并提出了移除断言、增加重试机制、优雅降级等改进方案。该案例揭示了资源受

小旭的专栏 677

Linux C/C++ 学习日记(49):线程池

本文总结了线程池的核心概念与实现要点:线程池是一种预先创建可复用线程的资源管理机制,通过维护线程集合来避免频繁创建/销毁线程的开销。其核心解决异步执行耗时任务和充分利用多核的问题。实现采用生产者-消费者模型,关键设计包括队列结构(单/双队列、优先级队列等)和线程数量管理(CPU密集型/IO密集型场景下的线程数计算)。代码实现要点涉及互斥锁、条件变量等同步原语的使用,并对比了单队列和双队列设计的性能差异。文章还提供了固定线程池的C++实现示例,涵盖任务提交、线程工作循环和队列管理等核心功能。

2302_79943247的博客 770

深度学习工具包 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")

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

linux---线程池种类以及实现(固定数量)

线程池是什么 一堆固定的数量的或者有最大数量限制的线程+任务队列->用于我们并发处理请求,避免了大量频繁的线程的创建和销毁的事件成本,同时避免了峰值压力带来瞬间大量线程被创建资源耗尽,程序奔溃的危险。 线程池的参数 corepollsize:核心池的大小,默认情况下,在创建线程池后,每当有新的任务 maximumpoolsize:线程池中最多可以创建的线程数 keeplivetime:线程...

boke_fengwei 1185

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Linux线程池

半同步 / 半反应堆线程池的实现 这里我们实现了一个半同步 / 半反应堆并发模式的线程池,代码清单见https://github.com/walkerczb/threadpool 中的 threadpool.h 。该线程池使用一个工作队列完全解除了主线程和工作线程的耦合关系:主线程往工作队列中插入任务,工作线程通过竞争来取得任务并执行它。不过,如果要将该线程池应用到实际服务器程序中,那么我们

Al_xin的专栏 1183

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

linux下C 线程池的原理讲解和代码实现(能自行伸缩扩展线程数)

转自 : http://lonelyc.blog.51cto.com/8072409/1315434 什么线程池,为什么要使用线程池?下面是一个比喻。 阶段一、一个医院,每天面对成千上万的病人,处理方式是:来一个病人找来一个医生处理,处理完了医生也走了。当看病时间较短的时候,医生来去的时间,显得尤为费时了。 阶段二、医院引进了线程池的概念。设置门诊,把医生全派出去坐诊

xiaoxianerqq的专栏 1066

看完就能找到工作!linux卸载mysql命令

专题5:Java序列化 1、什么是java序列化,如何实现java序列化? 2、保存(持久化)对象及其状态到内存或者磁盘 3、序列化对象以字节数组保持-静态成员不保存 4、序列化用户远程对象传输 5、Serializable 实现序列化 6、writeObject 和 readObject 自定义序列化策略 7、序列化 ID 8、序列化并不保存静态变量 9、Transient 关键字阻止该变量被序列化到文件中 10、序列化(深 clone 一中实现) 专题6:J

m0_56222134的博客 94

在线考试系统java代码,实战案例

前言 众所皆知的,Linux的核心原型是1991年由托瓦兹(Linus Torvalds)写出来的,但是托瓦兹为何可以写出Linux这个操作系统?为什么它要选择386的计算机来开发?为什么Linux的发展可以这么迅速?又为什么Linux是免费的?以及目前为何有这么多的 Linux版本(distributions)呢?了解这些东西后,才能够知道为何Linux可以免除专利软件之争,并且了解到Linux为何可以同时在个人计算机与大型主机上面大放异彩!所以,在实际进入Linux 的世界前,就让我们来谈一谈这些有趣的

m0_57286518的博客 224

总结二:linux面经

GDB调试:gdb调试的是可执行文件,在gcc编译时加入 -g ,告诉gcc在编译时加入调试信息,这样gdb才能调试这个被编译的文件quit:退出gdb,结束调试list:查看程序源代码list 5,10:显示5到10行的代码list test.c:5, 10: 显示源文件5到10行的代码,在调试多个文件时使用list get_sum: 显示get_sum函数周围的代码list test,c get_sum: 显示源文件get_sum函数周围的代码,在调试多个文件时使用。

weixin_54447296的博客 3710

一起学习epoll

epoll是Linux内核中的一种可扩展IO事件处理机制,最早在 Linux 2.5.44内核中引入,可被用于代替POSIX select 和 poll 系统调用,并且在具有大量应用程序请求时能够获得较好的性能( 此时被监视的文件描述符数目非常大,与旧的 select 和 poll 系统调用完成操作所需 O(n) 不同, epoll能在O(1)时间内完成操作,所以性能相当高),epo...

weixin_30695195的博客 131

linux面试问题汇总_2024linux运维面试题

46 | 给出一个个微信用户的好友关系对,将这些用户分成两组,每组内的用户全都互相不是好友。单例模式、简单工厂模式、工厂模式、抽象工厂模式、策略模式、观察者模式、组合模式、适配器模式、装饰模式、代理模式、外观模式 | || 83 | 千万级的用户,提供一个服务,该服务有很多模块,现在有一个底层模块需要优化,问怎么实现,在不影响其他服务模块以及用户体验的情况下。| 151 | 各种排序:冒泡、选择、插入、希尔、归并、快排、堆排、桶排、基数的原理、平均时间复杂度、最坏时间复杂度、空间复杂度、是否稳定。

2401_86358971的博客 837

linux多线程示例

1 #include <stdio.h> 2 #include <unistd.h> 3 #include <stdlib.h> 4 #include <pthread.h> 5 6 typedef void* (*fun)(void*); 7 8 fun fun1, fun2; 9 10 pthread...

weixin_34248849的博客 75

Linux 操作系统有关知识整理

总结了操作系统的重要知识点。包括Linux操作系统的应用编程如进程,线程等 和 网路编程中 socket 网络通信 TCP/IP等重点知识

m0_65745608的博客 457

51c~C++合集1

举一个例子,当我们的线程池中有100个任务,开了50个线程,当有49个线程都在工作时,此时还剩下一个任务没有执行,显而易见应当是剩下的那个线程去偷取剩下的一个任务,但是如果我们有30个任务组盛放了这100的任务,此时剩下的一个任务还不知道被放在哪里了呢。当然不是,我们可以设置一个缓存空间的最大任务数量,当传入的任务缓存满时,我们可以让后面的任务等一等不要着急,当任务队列中的任务减少的时候,我们就让缓存队列中的任务读出加入任务队列,同时写入新的任务。需要说明的是,真实的多线程情况远比我们刚才讨论的复杂。

whaosoft~aiotの开发板商城 1250

linux网络编程第二版百度网盘,2024年Java岗位BAT大厂面试题知识点小结

1、java事件机制包括哪三个部分?分别介绍。2、为什么要使用线程池?3、线程池有什么作用?4、说说几种常见的线程池及使用场景。5、线程池都有哪几种工作队列?6、怎么理解无界队列和有界队列?7、线程池中的几种重要的参数及流程说明。8、什么是反射机制?9、说说反射机制的作用。10、反射机制会不会有性能问题?11、你怎么理解http协议?12、说说http协议的工作流程。13、http有哪些请求提交方式?

VIP129370的博客 840
上一篇: 【Linux常见问题解决】Ubuntu Kylin 16.04 LTS 闪屏问题
下一篇: 【Linux学习笔记50】socket编程之TCP协议
RayCongLiang
博客等级 码龄9年 51粉丝 94原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值