一个例子展开,介绍Linux下面线程的操作、多线程的同步和互斥。

ffmpeg 4.4 cenc-aes-ctr 加解密 MP4 工程性质分析 阅读详情

前言

线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步、互斥,这些东西将在本文中介绍。我在某QQ群里见到这样一道面试题:

是否熟悉POSIX多线程编程技术?如熟悉,编写程序完成如下功能:

1)有一int型全局变量g_Flag初始值为0;

2) 在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为1

3) 在主线称中启动线程2,打印“this is thread2”,并将g_Flag设置为2

4) 线程序1需要在线程2退出后才能退出

5) 主线程在检测到g_Flag从1变为2,或者从2变为1的时候退出

我们带着这题开始这篇文章,结束之后,大家就都会做了。本文的框架如下:

  • 1、进程与线程
  • 2、使用线程的理由
  • 3、有关线程操作的函数
  • 4、线程之间的互斥
  • 5、线程之间的同步
  • 6、试题最终代码

1、进程与线程

进程是程序执行时的一个实例,即它是程序已经执行到何种程度的数据结构的汇集。从内核的观点看,进程的目的就是担当分配系统资源(CPU时间、内存等)的基本单位。

线程是进程的一个执行流,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。一个进程由几个线程组成(拥有很多相对独立的执行流的用户程序共享应用程序的大部分数据结构),线程与同属一个进程的其他的线程共享进程所拥有的全部资源。

"进程——资源分配的最小单位,线程——程序执行的最小单位"

进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其它进程产生影响,而线程只是一个进程中的不同执行路径。线程有自己的堆栈和局部变量,但线程没有单独的地址空间,一个线程死掉就等于整个进程死掉,所以多进程的程序要比多线程的程序健壮,但在进程切换时,耗费资源较大,效率要差一些。但对于一些要求同时进行并且又要共享某些变量的并发操作,只能用线程,不能用进程。

2、使用线程的理由

从上面我们知道了进程与线程的区别,其实这些区别也就是我们使用线程的理由。总的来说就是:进程有独立的地址空间,线程没有单独的地址空间(同一进程内的线程共享进程的地址空间)。(下面的内容摘自Linux下的多线程编程)

使用多线程的理由之一是和进程相比,它是一种非常"节俭"的多任务操作方式。我们知道,在Linux系统下,启动一个新的进程必须分配给它独立的地址空间,建立众多的数据表来维护它的代码段、堆栈段和数据段,这是一种"昂贵"的多任务工作方式。而运行于一个进程中的多个线程,它们彼此之间使用相同的地址空间,共享大部分数据,启动一个线程所花费的空间远远小于启动一个进程所花费的空间,而且,线程间彼此切换所需的时间也远远小于进程间切换所需要的时间。据统计,总的说来,一个进程的开销大约是一个线程开销的30倍左右,当然,在具体的系统上,这个数据可能会有较大的区别。

使用多线程的理由之二是线程间方便的通信机制。对不同进程来说,它们具有独立的数据空间,要进行数据的传递只能通过通信的方式进行,这种方式不仅费时,而且很不方便。线程则不然,由于同一进程下的线程之间共享数据空间,所以一个线程的数据可以直接为其它线程所用,这不仅快捷,而且方便。当然,数据的共享也带来其他一些问题,有的变量不能同时被两个线程所修改,有的子程序中声明为static的数据更有可能给多线程程序带来灾难性的打击,这些正是编写多线程程序时最需要注意的地方。

除了以上所说的优点外,不和进程比较,多线程程序作为一种多任务、并发的工作方式,当然有以下的优点:

  • 提高应用程序响应。这对图形界面的程序尤其有意义,当一个操作耗时很长时,整个系统都会等待这个操作,此时程序不会响应键盘、鼠标、菜单的操作,而使用多线程技术,将耗时长的操作(time consuming)置于一个新的线程,可以避免这种尴尬的情况。
  • 使多CPU系统更加有效。操作系统会保证当线程数不大于CPU数目时,不同的线程运行于不同的CPU上。
  • 改善程序结构。一个既长又复杂的进程可以考虑分为多个线程,成为几个独立或半独立的运行部分,这样的程序会利于理解和修改。

=============================

从函数调用上来说,进程创建使用fork()操作;线程创建使用clone()操作。Richard Stevens大师这样说过:

  • fork is expensive. Memory is copied from the parent to the child, all descriptors are duplicated in the child, and so on. Current implementations use a technique called copy-on-write, which avoids a copy of the parent's data space to the child until the child needs its own copy. But, regardless of this optimization, fork is expensive.

  • IPC is required to pass information between the parent and child after the fork. Passing information from the parent to the child before the fork is easy, since the child starts with a copy of the parent's data space and with a copy of all the parent's descriptors. But, returning information from the child to the parent takes more work.

Threads help with both problems. Threads are sometimes called lightweight processes since a thread is "lighter weight" than a process. That is, thread creation can be 10–100 times faster than process creation.

All threads within a process share the same global memory. This makes the sharing of information easy between the threads, but along with this simplicity comes the problem of synchronization.

=============================

3、有关线程操作的函数

#include <pthread.h>
 
int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*func) (void *), void *arg);
int pthread_join (pthread_t tid, void ** status);
pthread_t pthread_self (void);
int pthread_detach (pthread_t tid);
void pthread_exit (void *status);

pthread_create用于创建一个线程,成功返回0,否则返回Exxx(为正数)。

  • pthread_t *tid:线程id的类型为pthread_t,通常为无符号整型,当调用pthread_create成功时,通过*tid指针返回。
  • const pthread_attr_t *attr:指定创建线程的属性,如线程优先级、初始栈大小、是否为守护进程等。可以使用NULL来使用默认值,通常情况下我们都是使用默认值。
  • void *(*func) (void *):函数指针func,指定当新的线程创建之后,将执行的函数。
  • void *arg:线程将执行的函数的参数。如果想传递多个参数,请将它们封装在一个结构体中。

pthread_join用于等待某个线程退出,成功返回0,否则返回Exxx(为正数)。

  • pthread_t tid:指定要等待的线程ID
  • void ** status:如果不为NULL,那么线程的返回值存储在status指向的空间中(这就是为什么status是二级指针的原因!这种才参数也称为“值-结果”参数)。

pthread_self用于返回当前线程的ID。

pthread_detach用于是指定线程变为分离状态,就像进程脱离终端而变为后台进程类似。成功返回0,否则返回Exxx(为正数)。变为分离状态的线程,如果线程退出,它的所有资源将全部释放。而如果不是分离状态,线程必须保留它的线程ID,退出状态直到其它线程对它调用了pthread_join。

进程也是类似,这也是当我们打开进程管理器的时候,发现有很多僵死进程的原因!也是为什么一定要有僵死这个进程状态。

pthread_exit用于终止线程,可以指定返回值,以便其他线程通过pthread_join函数获取该线程的返回值。

  • void *status:指针线程终止的返回值。

知道了这些函数之后,我们试图来完成本文一开始的问题:

1)有一int型全局变量g_Flag初始值为0;

2)在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为1

3)在主线称中启动线程2,打印“this is thread2”,并将g_Flag设置为2

这3点很简单嘛!!!不就是调用pthread_create创建线程。代码如下:

/*
 * 1)有一int型全局变量g_Flag初始值为0;
 *
 * 2)在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为1
 *
 * 3)在主线称中启动线程2,打印“this is thread2”,并将g_Flag设置为2
 *
 */
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<errno.h>
#include<unistd.h>

int g_Flag=0;

void* thread1(void*);
void* thread2(void*);

/*
 * when program is started, a single thread is created, called the initial thread or main thread.
 * Additional threads are created by pthread_create.
 * So we just need to create two thread in main().
 */
int main(int argc, char** argv)
{
	printf("enter main\n");
	pthread_t tid1, tid2;
	int rc1=0, rc2=0;
	rc2 = pthread_create(&tid2, NULL, thread2, NULL);
	if(rc2 != 0)
		printf("%s: %d\n",__func__, strerror(rc2));

	rc1 = pthread_create(&tid1, NULL, thread1, &tid2);
	if(rc1 != 0)
		printf("%s: %d\n",__func__, strerror(rc1));
	printf("leave main\n");
	exit(0);	
}
/*
 * thread1() will be execute by thread1, after pthread_create()
 * it will set g_Flag = 1;
 */
void* thread1(void* arg)
{
	printf("enter thread1\n");
	printf("this is thread1, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());
	g_Flag = 1;
	printf("this is thread1, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());
	printf("leave thread1\n");
	pthread_exit(0);
}

/*
 * thread2() will be execute by thread2, after pthread_create()
 * it will set g_Flag = 2;
 */
void* thread2(void* arg)
{
	printf("enter thread2\n");
	printf("this is thread2, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());
	g_Flag = 2;
	printf("this is thread1, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());
	printf("leave thread2\n");
	pthread_exit(0);
}

这样就完成了1)、2)、3)这三点要求。编译执行得如下结果:

netsky@ubuntu:~/workspace/pthead_test$ gcc -lpthread test.c

如果程序中使用到了pthread库中的函数,除了要#include<pthread.h>,在编译的时候还有加上-lpthread 选项。 
netsky@ubuntu:~/workspace/pthead_test$ ./a.out 
enter main 
enter thread2 
this is thread2, g_Flag: 0, thread id is 3079588720 
this is thread1, g_Flag: 2, thread id is 3079588720 
leave thread2 
leave main 
enter thread1 
this is thread1, g_Flag: 2, thread id is 3071196016 
this is thread1, g_Flag: 1, thread id is 3071196016 
leave thread1 
但是运行结果不一定是上面的,还有可能是:

netsky@ubuntu:~/workspace/pthead_test$ ./a.out 
enter main 
leave main 
enter thread1 
this is thread1, g_Flag: 0, thread id is 3069176688 
this is thread1, g_Flag: 1, thread id is 3069176688 
leave thread1

或者是:

netsky@ubuntu:~/workspace/pthead_test$ ./a.out 
enter main 
leave main 
等等。这也很好理解因为,这取决于主线程main函数何时终止,线程thread1、thread2是否能够来得急执行它们的函数。这也是多线程编程时要注意的问题,因为有可能一个线程会影响到整个进程中的所有其它线程!如果我们在main函数退出前,sleep()一段时间,就可以保证thread1、thread2来得及执行。

吸血蝙蝠Attention:大家肯定已经注意到了,我们在线程函数thread1()、thread2()执行完之前都调用了pthread_exit。如果我是调用exit()又或者是return会怎样呢?自己动手试试吧!

pthread_exit()用于线程退出,可以指定返回值,以便其他线程通过pthread_join()函数获取该线程的返回值。 
return是函数返回,只有线程函数return,线程才会退出。 
exit是进程退出,如果在线程函数中调用exit,进程中的所有函数都会退出!

“4) 线程序1需要在线程2退出后才能退出”第4点也很容易解决,直接在thread1的函数退出之前调用pthread_join就OK了。

4、线程之间的互斥

上面的代码似乎很好的解决了问题的前面4点要求,其实不然!!!因为g_Flag是一个全局变量,线程thread1和thread2可以同时对它进行操作,需要对它进行加锁保护,thread1和thread2要互斥访问才行。下面我们就介绍如何加锁保护——互斥锁。

互斥锁:

使用互斥锁(互斥)可以使线程按顺序执行。通常,互斥锁通过确保一次只有一个线程执行代码的临界段来同步多个线程。互斥锁还可以保护单线程代码。

互斥锁的相关操作函数如下:

#include <pthread.h> 

int pthread_mutex_lock(pthread_mutex_t * mptr); 
int pthread_mutex_unlock(pthread_mutex_t * mptr); 
//Both return: 0 if OK, positive Exxx value on error

在对临界资源进行操作之前需要pthread_mutex_lock先加锁,操作完之后pthread_mutex_unlock再解锁。而且在这之前需要声明一个pthread_mutex_t类型的变量,用作前面两个函数的参数。具体代码见第5节。

5、线程之间的同步

第5点——主线程在检测到g_Flag从1变为2,或者从2变为1的时候退出。就需要用到线程同步技术!线程同步需要条件变量。

条件变量:

使用条件变量可以以原子方式阻塞线程,直到某个特定条件为真为止。条件变量始终与互斥锁一起使用。对条件的测试是在互斥锁(互斥)的保护下进行的。

如果条件为假,线程通常会基于条件变量阻塞,并以原子方式释放等待条件变化的互斥锁。如果另一个线程更改了条件,该线程可能会向相关的条件变量发出信号,从而使一个或多个等待的线程执行以下操作:

  • 唤醒
  • 再次获取互斥锁
  • 重新评估条件

在以下情况下,条件变量可用于在进程之间同步线程:

  • 线程是在可以写入的内存中分配的
  • 内存由协作进程共享

“使用条件变量可以以原子方式阻塞线程,直到某个特定条件为真为止。”即可用到第5点,主线程main函数阻塞于等待g_Flag从1变为2,或者从2变为1。条件变量的相关函数如下:

#include <pthread.h>
 
int pthread_cond_wait(pthread_cond_t *cptr, pthread_mutex_t *mptr); 
int pthread_cond_signal(pthread_cond_t *cptr); 
//Both return: 0 if OK, positive Exxx value on error

pthread_cond_wait用于等待某个特定的条件为真,pthread_cond_signal用于通知阻塞的线程某个特定的条件为真了。在调用者两个函数之前需要声明一个pthread_cond_t类型的变量,用于这两个函数的参数。

为什么条件变量始终与互斥锁一起使用,对条件的测试是在互斥锁(互斥)的保护下进行的呢?因为“某个特性条件”通常是在多个线程之间共享的某个变量。互斥锁允许这个变量可以在不同的线程中设置和检测。

通常,pthread_cond_wait只是唤醒等待某个条件变量的一个线程。如果需要唤醒所有等待某个条件变量的线程,需要调用:

int pthread_cond_broadcast (pthread_cond_t * cptr);

默认情况下面,阻塞的线程会一直等待,知道某个条件变量为真。如果想设置最大的阻塞时间可以调用:

int pthread_cond_timedwait (pthread_cond_t * cptr, pthread_mutex_t *mptr, const struct timespec *abstime);

如果时间到了,条件变量还没有为真,仍然返回,返回值为ETIME。

6、试题最终代码

通过前面的介绍,我们可以轻松的写出代码了,如下所示:

/*
 是否熟悉POSIX多线程编程技术?如熟悉,编写程序完成如下功能:
  1)有一int型全局变量g_Flag初始值为0;
  2)在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为1
  3)在主线称中启动线程2,打印“this is thread2”,并将g_Flag设置为2
  4)线程序1需要在线程2退出后才能退出
  5)主线程在检测到g_Flag从1变为2,或者从2变为1的时候退出
   */
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<errno.h>
#include<unistd.h>

typedef void* (*fun)(void*);

int g_Flag=0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* thread1(void*);
void* thread2(void*);

/*
 *  when program is started, a single thread is created, called the initial thread or main thread.
 *  Additional threads are created by pthread_create.
 *  So we just need to create two thread in main().
 */

int main(int argc, char** argv)
{
	printf("enter main\n");
	pthread_t tid1, tid2;
	int rc1=0, rc2=0;
	rc2 = pthread_create(&tid2, NULL, thread2, NULL);
	if(rc2 != 0)
		printf("%s: %d\n",__func__, strerror(rc2));

	rc1 = pthread_create(&tid1, NULL, thread1, &tid2);
	if(rc1 != 0)
		printf("%s: %d\n",__func__, strerror(rc1));

	pthread_cond_wait(&cond, &mutex);
	printf("leave main\n");
	exit(0);	
}

/*
 * thread1() will be execute by thread1, after pthread_create()
 * it will set g_Flag = 1;
 */
void* thread1(void* arg)
{
	printf("enter thread1\n");
	printf("this is thread1, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());
	pthread_mutex_lock(&mutex);
	if(g_Flag == 2)
		pthread_cond_signal(&cond);
	g_Flag = 1;
	printf("this is thread1, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());
	pthread_mutex_unlock(&mutex);
	pthread_join(*(pthread_t*)arg, NULL);
	printf("leave thread1\n");
	pthread_exit(0);
}

/*
 * thread2() will be execute by thread2, after pthread_create()
 * it will set g_Flag = 2;
 */
void* thread2(void* arg)
{
	printf("enter thread2\n");
	printf("this is thread2, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());
	pthread_mutex_lock(&mutex);
	if(g_Flag == 1)
		pthread_cond_signal(&cond);
	g_Flag = 2;
	printf("this is thread2, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());
	pthread_mutex_unlock(&mutex);
	printf("leave thread2\n");
	pthread_exit(0);
}

编译运行可以得到符合要求的结果!

本文将详细介绍如何在 Qt (C++) 应用程序中集成 osgEarth,加载三维数字地球,并在指定经纬度添加三维模型(如飞机、建筑等)。 OSG 与 Qt 的交互通常需要处理 OpenGL 上下文。osgEarth 3.x 提供了对 Qt 的较好支持,或者可以使用。在普通 OSG 程序中,你需要手动处理坐标系转换将经纬度转为笛卡尔坐标 (XYZ)。这是实现的关键,将 OSG 的渲染循环集成到 Qt 的事件循环中。第三方库,但在本教程中,我们将展示一种通过继承。,将 Qt 的输入事件转换为 OSG 理解的。事件,这是实现交互(旋转地球、缩放)的基础。来嵌入 OSG 视图的标准方法。在这里我们初始化地球并添加模型。节点简化了这一过程。 阅读详情

相关推荐

SAP CO实战:如何用KKA2/CJ88结果分析码搞定项目收入成本匹配(附真实案例)

本文深入解析了SAP CO模块中结果分析码KKA2/CJ88的核心应用,通过真实案例详细阐述了如何在成本波动剧烈的销售型项目中,运用结果分析实现收入与成本的精准匹配。文章重点拆解了不同结果分析方法的适用场景与财务影响,并提供了从配置、操作到问题排查的完整实战指南,帮助财务顾问提升项目财务管理能力。

qsc9012345的博客 607

Linux多线程——使用互斥量同步线程

前文再续,书接上一回,在上一篇文章:Linux多线程——使用信号量同步线程中,我们留下了一个如何使用互斥量来进行线程同步的问题,本文将会给出互斥量的详细解说,并用一个互斥量解决上一篇文章中,要使用两个信号量才能解决的只有子线程结束了对输入的处理和统计后,主线程才能继续执行的问题。 一、什么是互斥量 互斥量是另一种用于多线程中的同步访问方法,它允许程序锁住某个对象,使得每次只能有一个线程...

haierboos 336

数字IC后端层次化Hierarchical Flow子系统Sub-System模块 block partition和pin assignment细节盘点

数字IC后端培训教程之Hierarchical Flow子系统block partition和pin assignment详细教程

weixin_37584728的博客 1604

Linux多线程编程(二)---线程之间的同步与互斥

由于线程共享进程的资源和地址空间,因此在对这些资源进行操作时,必须考虑到线程间资源访问的同步与互斥问题。这里主要介绍Posix中两种线程同步机制,分别为互斥锁和信号量。这两个同步机制可以通过互相调用对方来实现,但互斥锁更适用于同时可用的资源是唯一的情况;信号量更适用于同时可用的资源为多个的情况。

王文松的博客 1万+

【RL in VLA】VLA中的强化学习

本文提出了一种名为 Reinforcement Learning Distilled Generalist(RLDG) 的方法,通过强化学习生成高质量训练数据来微调机器人基础模型。通过在多个精确操作任务上的实验,我们证明了 RLDG 在成功率和泛化能力上显著优于使用人类演示的传统微调方法。RLDG 不仅减少了对人类演示数据的依赖,还展示了在复杂多阶段任务中的灵活性和有效性。

三木今天学习了嘛の博客 2257

告别商业软件?实测用gnina(CNN打分版)做分子对接:从安装到跑通第一个案例

本文详细介绍了基于卷积神经网络(CNN)的开源分子对接工具gnina的安装与实战应用。从环境配置、编译安装到运行第一个COVID-19主蛋白酶抑制剂对接案例,全面解析了这款替代商业软件的强大功能,特别适合预算有限的研究团队进行药物发现和虚拟筛选。

weixin_42522320的博客 255

本文一个例子展开,介绍Linux下面线程的操作、多线程的同步和互斥

from :  http://www.cnblogs.com/skynet/archive/2010/10/30/1865267.html 前言 线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步、互斥,这些东西将在本文中介绍。我在某QQ群里见到这样一道面试题: 是否熟悉POSIX多线程编程技术

Adrian 博客 847

【R语言】富集分析可视化代码(整理版)

分别介绍了如何使用DAVID在线分析工具对基因进行GO/KEGG功能富集分析、使用R ggplot包对获得的基因GO/KEGG功能富集结果进行可视化、使用R clusterProfiler包和R AnnotationHub包对基因进行GO/KEGG功能富集分析、OrgDb包制作以及结果可视化等。故,我重新整理了一波,并补充了可对多个分组的富集结果进行可视化以及富集结果绘制圈图等的代码。关注“在打豆豆的小潘学长”公众号,发送“富集分析3”获得完整代码包和演示数据。一、单组富集结果可视化。

weixin_54004950的博客 1万+

Linux多线程编程(不限Linux)——本文一个例子展开,介绍Linux下面线程的操作、多线程的同步和互斥。

前言 线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步、互斥,这些东西将在本文中介绍。我在某QQ群里见到这样一道面试题: 是否熟悉POSIX多线程编程技术?如熟悉,编写程序完成如下功能: 1)有一int型全局变量g_Flag初始值为0; 2) 在主线称中起动线程1,打印“this is thread1”,并将g_F

overstack的专栏 745

AMBA VIP基础使用方式(AXI)

AXI环境配置 1)基础配置 作为master或者slave使用时,对应的is_active = 1 只作为i监测(monitor)使用时,对应slave_cfg的is_active = 0(对应端口连接也有所区别) class smu_axi_cfg extends svt_axi_system_configuration; `uvm_object_utils(smu_aix_cfg) function new(string name="smu_axi_cfg); super.new(n..

qq_37573794的博客 7984

Java 新纪元 — JDK 25 + Spring Boot 4 全栈实战(十九):微服务实战——Boot 4 + Spring Cloud 2026.x,构建高并发电商分布式系统

Component@Slf4j@Autowired// 白名单路径@Override// 白名单放行// 提取Token// 传递用户信息到下游服务.mutate().build();@Override// 最高优先级if (bearer!@Component技术点Boot 3 时代Boot 4 时代提升线程模型平台线程池(200线程上限)虚拟线程(百万级并发)50x+服务通信。

qq_17204557的博客 185

Linux下面线程的操作、多线程的同步和互斥

​——本文一个例子展开,介绍Linux下面线程的操作、多线程的同步和互斥。前言线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步、互斥,这些东西将在本文中介绍。我在某QQ群里见到这样一道面试题:是否熟悉POSIX多线程编程技术?如熟悉,编写程序完成如下功能:1)有一int型全局变量g_Flag初始值为0;2)在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为1。

szxhcljyjsjdff的博客 719

ISP算法:宽动态HDR

动态范围(Dynamic Range):在很多领域来表示某个变量的最大值和最小值的比值。在数字图像处理领域里,动态范围也被称为图像对比度,表示图像可以显示范围内,像素最大亮度值和最小亮度值的比值。 高动态范围图像(High Dynamic Range Image): 可以反映真实场景中高动态范围亮度信息图像。 高动态技术:能自动调整图像动态范围的一种技术。该技术是一种利用计算机高速运算产生高

a200800170331的专栏 1万+

Linux下线程的同步与互斥

开头我们来写一个简单的程序,实现用多线程的方式来抢票,代码如下:运行完结果后发现,我这只有一万张票,在if条件判断里我也做了判断,怎么会干到-2来了呢?运用线程的理论知识我们知道,ticketnum在线程中属于共享资源,它不具有原子性,在我们需要对变量进行减减的时候,内存会将变量存入cpu中减减,然后再把减完后的内容写入内存里三步,

pouop的博客 811

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

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

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

linux 多线程编程 同步与互斥

——本文一个例子展开,介绍Linux下面线程的操作、多线程的同步和互斥。 前言 线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步、互斥,这些东西将在本文中介绍。我在某QQ群里见到这样一道面试题: 是否熟悉POSIX多线程编程技术?如熟悉,编写程序完成如下功能: 1)有一int型全局变量g_Flag初始值为0; 2

zhuomun的专栏 1212

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

介绍Linux下面线程的操作、多线程的同步和互斥

——本文一个例子展开,介绍Linux下面线程的操作、多线程的同步和互斥。 前言 线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步、互斥,这些东西将在本文中介绍。我在某QQ群里见到这样一道面试题: 是否熟悉POSIX多线程编程技术?如熟悉,编写程序完成如下功能: 1)有一int型全局变量g_Flag初始值为0; 2

gmaker2020的专栏 484

linux多线程编程 同步与互斥

——本文一个例子展开,介绍Linux下面线程的操作、多线程的同步和互斥。 前言 线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步、互斥,这些东西将在本文中介绍。我在某QQ群里见到这样一道面试题: 是否熟悉POSIX多线程编程技术?如熟悉,编写程序完成如下功能: 1)有一int型全局变量g_Flag初始值为0; 2

MMT的专栏 627

讲Linux下面线程的操作、多线程的同步和互斥相关函数及操作的文章链接

Linux多线程编程(不限Linux) http://www.cnblogs.com/skynet/archive/2010/10/30/1865267.html Linux多线程编程详细解析----条件变量 pthread_cond_t http://blog.csdn.net/sunboy_2050/article/details/6031723 pthre

liziyun537的专栏 1140

Linux多线程编程(不限Linux)转

——本文一个例子展开,介绍Linux下面线程的操作、多线程的同步和互斥。 前言 线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步、互斥,这些东西将在本文中介绍。我在某QQ群里见到这样一道面试题: 是否熟悉POSIX多线程编程技术?如熟悉,编写程序完成如下功能: 1)有一int型全局变量g_Flag初始值...

119

Linux多线程编程(不限Linux)

线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步、互斥,这些东西将在本文中介绍。我在某QQ群里见到这样一道面试题:是否熟悉POSIX多线程编程技术?如熟悉,编写程序完成如下功能:1)有一int型全局变量g_Flag初始值为0;2) 在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为13) 在主线称中启动线程2,打印“this is thread2”,并将g_Flag设置为2。

Chocolate的博客 125

【线程安全】线程互斥的原理

即使是多处理器平台,访问内存的 总线周期也有先后,一个处理器上的交换指令执行时另一个处理器的交换指令只能等待总线周期。线程互斥(Mutual Exclusion)是多线程编程中的一个重要概念,用于解决。要想做到一个线程访问临界区时阻止其它线程访问,我们就需要使用到。:指向互斥锁属性对象的指针。对某个互斥量进行加锁或者解锁,成功返回0,失败返回错误码。为了方便阐述,后面出现的锁和互斥量不做过多区分。表示上锁(),上锁之后其他线程不能访问临界区,上图中表示使用互斥锁实现线程互斥的示意图,

稻草人敲代码的博客 2415

Linux下的多线程编程

转: Linux下的多线程编程 代码改变世界 Posts - 106, Articles

stevedusunan的博客 513

Linux线程同步技术简介

线程同步技术摘要 互斥锁和条件变量是Linux线程同步的核心技术。互斥锁通过pthread_mutex_init/init初始化和销毁,提供lock/unlock操作保护临界区,需注意死锁问题。条件变量解决互斥锁的忙等待问题,配合互斥锁使用,当条件不满足时线程休眠,通过pthread_cond_wait自动释放锁,生产者通过pthread_cond_signal/broadcast唤醒消费者。条件变量使用时需遵循标准模式:加锁后循环检查条件,避免虚假唤醒。这两种机制共同构建了线程间安全高效的同步通信基础。

qq_53525217的博客 808

(Linux多线程编程(不限Linux))多线程操作

过去对于进程和线程的理解一直就不清楚, 马上要用到多线程和进程, 这里转载一篇博客,感觉挺有用的, 介绍了大部分线程的东西希望有用。 Linux多线程编程(不限Linux) 2010-10-30 20:58 by 吴秦, 20765 visits, 收藏,

tietao的专栏 2324

linux 互斥锁销毁_Linux 互斥锁

互斥的概念在多线程编程中,引入了对象互斥锁的概念,来保证共享数据操作的完整性。 每个对象都对应于一个可称为" 互斥锁" 的标记,这个标记用来保证在任一时刻, 只能有一个线程访问该对象。互斥锁操作互斥锁也可以叫线程锁,接下来说说互斥锁的的使用方法。对互斥锁进行操作的函数,常用的有如下几个:#include int pthread_mutex_destroy(pthread_mutex_t *mute...

weixin_39561168的博客 557
上一篇: 从ramdisk根文件系统启动Linux成功,及使用initramfs启动linux
下一篇: 触摸屏驱动
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值