linux下多线程(pthread)编程实例,Linux下多线程(pthread)编程实例

Linux下多线程(pthread)编程实例

2018-12-18

Linux下多线程(pthread)编程实例

Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。顺便说一下,Linux 下pthread的实现是通过系统调用clone()来实现的。clone()是 Linux所特有的系统调用,它的使用方式类似fork,关于clone()的详细情况,有兴趣的读者可以去查看有关文档说明。下面我们展示一个最简单的多线程程序 pthread_create.c。

一个重要的线程创建函数原型:

#include

int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr, void *(*start_rtn)(void),void *restrict arg);

返回值:若是成功建立线程返回0,否则返回错误的编号

形式参数:

pthread_t *restrict tidp 要创建的线程的线程id指针

const pthread_attr_t *restrict attr 创建线程时的线程属性

void* (start_rtn)(void) 返回值是void类型的指针函数

void *restrict arg start_rtn的行参

例程1:

功能:创建一个简单的线程

程序名称:pthread_create.c

/********************************************************************************************

** Name:pthread_create.c

** Used to study the multithread programming in Linux OS

** Author:zeickey

** Date:2006/9/16

** Copyright (c) 2006,All Rights Reserved!

*********************************************************************************************/

#include

#include

void *myThread1(void)

{

int i;

for (i=0; i<100; i++)

{

printf("This is the 1st pthread,created by zieckey./n");

sleep(1);//Let this thread to sleep 1 second,and then continue to run

}

}

void *myThread2(void)

{

int i;

for (i=0; i<100; i++)

{

printf("This is the 2st pthread,created by zieckey./n");

sleep(1);

}

}

int main()

{

int i=0, ret=0;

pthread_t id1,id2;

ret = pthread_create(&id2, NULL, (void*)myThread1, NULL);

if (ret)

{

printf("Create pthread error!/n");

return 1;

}

ret = pthread_create(&id2, NULL, (void*)myThread2, NULL);

if (ret)

{

printf("Create pthread error!/n");

return 1;

}

pthread_join(id1, NULL);

pthread_join(id2, NULL);

return 0;

}

我们编译此程序:

# gcc pthread_create.c -lpthread

因为pthread的库不是linux系统的库,所以在进行编译的时候要加上-lpthread,否则编译不过,会出现下面错误

thread_test.c: 在函数 ‘create’ 中:

thread_test.c:7: 警告: 在有返回值的函数中,程序流程到达函数尾

/tmp/ccOBJmuD.o: In function `main":thread_test.c:(.text+0x4f):对‘pthread_create’未定义的引用

collect2: ld 返回 1

运行,我们得到如下结果:

# ./a.out

This is the 1st pthread,created by zieckey.

This is the 2st pthread,created by zieckey.

This is the 1st pthread,created by zieckey.

This is the 2st pthread,created by zieckey.

This is the 2st pthread,created by zieckey.

This is the 1st pthread,created by zieckey.

....

两个线程交替执行。

此例子介绍了创建线程的方法。

下面例子介绍向线程传递参数。

例程2:

功能:向新的线程传递整形值

程序名称:pthread_int.c

/********************************************************************************************

** Name:pthread_int.c

** Used to study the multithread programming in Linux OS

** Pass a parameter to the thread.

** Author:zeickey

** Date:2006/9/16

** Copyright (c) 2006,All Rights Reserved!

*********************************************************************************************/

#include

#include

#include

void *create(void *arg)

{

int *num;

num=(int *)arg;

printf("create parameter is %d /n",*num);

return (void *)0;

}

int main(int argc ,char *argv[])

{

pthread_t tidp;

int error;

int test=4;

int *attr=&test;

error=pthread_create(&tidp,NULL,create,(void *)attr);

if(error)

{

printf("pthread_create is created is not created ... /n");

return -1;

}

sleep(1);

printf("pthread_create is created .../n");

return 0;

}

编译方法:

gcc -lpthread pthread_int.c -Wall

执行结果:

create parameter is 4

pthread_create is created is created ...

例程总结:

可以看出来,我们在main函数中传递的整行指针,传递到我们新建的线程函数中。

在上面的例子可以看出来我们向新的线程传入了另一个线程的int数据,线程之间还可以传递字符串或是更复杂的数据结构。

例程3:

程序功能:向新建的线程传递字符串

程序名称:pthread_string.c

/********************************************************************************************

** Name:pthread_string.c

** Used to study the multithread programming in Linux OS

** Pass a ‘char*‘ parameter to the thread.

** Author:zeickey

** Date:2006/9/16

** Copyright (c) 2006,All Rights Reserved!

*********************************************************************************************/

#include

#include

#include

void *create(void *arg)

{

char *name;

name=(char *)arg;

printf("The parameter passed from main function is %s /n",name);

return (void *)0;

}

int main(int argc, char *argv[])

{

char *a="zieckey";

int error;

pthread_t tidp;

error=pthread_create(&tidp, NULL, create, (void *)a);

if(error!=0)

{

printf("pthread is not created./n");

return -1;

}

sleep(1);

printf("pthread is created... /n");

return 0;

}

编译方法:

gcc -Wall pthread_string.c -lpthread

执行结果:

The parameter passed from main function is zieckey

pthread is created...

例程总结:

可以看出来main函数中的字符串传入了新建的线程中。

例程4:

程序功能:向新建的线程传递字符串

程序名称:pthread_struct.c

/********************************************************************************************

** Name:pthread_struct.c

** Used to study the multithread programming in Linux OS

** Pass a ‘char*‘ parameter to the thread.

** Author:zeickey

** Date:2006/9/16

** Copyright (c) 2006,All Rights Reserved!

*********************************************************************************************/

#include

#include

#include

#include

struct menber

{

int a;

char *s;

};

void *create(void *arg)

{

struct menber *temp;

temp=(struct menber *)arg;

printf("menber->a = %d /n",temp->a);

printf("menber->s = %s /n",temp->s);

return (void *)0;

}

int main(int argc,char *argv[])

{

pthread_t tidp;

int error;

struct menber *b;

b=(struct menber *)malloc( sizeof(struct menber) );

b->a = 4;

b->s = "zieckey";

error = pthread_create(&tidp, NULL, create, (void *)b);

if( error )

{

printf("phread is not created.../n");

return -1;

}

sleep(1);

printf("pthread is created.../n");

return 0;

}

编译方法:

gcc -Wall pthread_struct.c -lpthread

执行结果:

menber->a = 4

menber->s = zieckey

pthread is created...

例程总结:

可以看出来main函数中的一个结构体传入了新建的线程中。

线程包含了标识进程内执行环境必须的信息。他集成了进程中的所有信息都是对线程进行共享的,包括文本程序、程序的全局内存和堆内存、栈以及文件描述符。

例程5:

程序目的:验证新建立的线程可以共享进程中的数据

程序名称:pthread_share.c

/********************************************************************************************

** Name:pthread_share_data.c

** Used to study the multithread programming in Linux OS

** Pass a ‘char*‘ parameter to the thread.

** Author:zeickey

** Date:2006/9/16

** Copyright (c) 2006,All Rights Reserved!

*********************************************************************************************/

#include

#include

#include

static int a=4;

void *create(void *arg)

{

printf("new pthread ... /n");

printf("a=%d /n",a);

return (void *)0;

}

int main(int argc,char *argv[])

{

pthread_t tidp;

int error;

a=5;

error=pthread_create(&tidp, NULL, create, NULL);

if(error!=0)

{

printf("new thread is not create ... /n");

return -1;

}

sleep(1);

printf("new thread is created ... /n");

return 0;

}

编译方法:

gcc -Wall pthread_share_data.c -lpthread

执行结果:

new pthread ...

a=5

new thread is created ...

例程总结:

可以看出来,我们在主线程更改了我们的全局变量a的值的时候,我们新建立的线程则打印出来了改变的值,可以看出可以访问线程所在进程中的数据信息。

2、线程的终止

如果进程中任何一个线程中调用exit,_Exit,或者是_exit,那么整个进程就会终止,

与此类似,如果信号的默认的动作是终止进程,那么,把该信号发送到线程会终止进程。

线程的正常退出的方式:

(1) 线程只是从启动例程中返回,返回值是线程中的退出码

(2) 线程可以被另一个进程进行终止

(3) 线程自己调用pthread_exit函数

两个重要的函数原型:

#include

void pthread_exit(void *rval_ptr);

/*rval_ptr 线程退出返回的指针*/

int pthread_join(pthread_t thread,void **rval_ptr);

/*成功结束进程为0,否则为错误编码*/

例程6

程序目的:线程正常退出,接受线程退出的返回码

程序名称:pthread_exit.c

/********************************************************************************************

** Name:pthread_exit.c

** Used to study the multithread programming in Linux OS

** A example showing a thread to exit and with a return code.

** Author:zeickey

** Date:2006/9/16

** Copyright (c) 2006,All Rights Reserved!

*********************************************************************************************/

#include

#include

#include

void *create(void *arg)

{

printf("new thread is created ... /n");

return (void *)8;

}

int main(int argc,char *argv[])

{

pthread_t tid;

int error;

void *temp;

error = pthread_create(&tid, NULL, create, NULL);

if( error )

{

printf("thread is not created ... /n");

return -1;

}

error = pthread_join(tid, &temp);

if( error )

{

printf("thread is not exit ... /n");

return -2;

}

printf("thread is exit code %d /n", (int )temp);

return 0;

}

编译方法:

gcc -Wall pthread_exit.c -lpthread

执行结果:

new thread is created ...

thread is exit code 8

例程总结:

可以看出来,线程退出可以返回线程的int数值。线程退出不仅仅可以返回线程的int数值,还可以返回一个复杂的数据结构。

例程7

程序目的:线程结束返回一个复杂的数据结构

程序名称:pthread_return_struct.c

#include

#include

#include

struct menber

{

int a;

char *b;

}temp={8,"zieckey"};

void *create(void *arg)

{

printf("new thread ... /n");

return (void *)&temp;

}

int main(int argc,char *argv[])

{

int error;

pthread_t tid;

struct menber *c;

error = pthread_create(&tid, NULL, create, NULL);

if( error )

{

printf("new thread is not created ... /n");

return -1;

}

printf("main ... /n");

error = pthread_join(tid,(void *)&c);

if( error )

{

printf("new thread is not exit ... /n");

return -2;

}

printf("c->a = %d /n",c->a);

printf("c->b = %s /n",c->b);

sleep(1);

return 0;

}

编译方法:

gcc -Wall pthread_return_struct.c -lpthread

执行结果:

main ...

new thread ...

c->a = 8

c->b = zieckey

例程总结:

一定要记得返回的数据结构要是在这个数据要返回的结构没有释放的时候应用,

如果数据结构已经发生变化,那返回的就不会是我们所需要的,而是脏数据

3、线程标识

函数原型:

#include

pthread_t pthread_self(void);

pid_t getpid(void);

getpid()用来取得目前进程的进程识别码,函数说明

例程8

程序目的:实现在新建立的线程中打印该线程的id和进程id

程序名称:pthread_id.c

/********************************************************************************************

** Name:pthread_id.c

** Used to study the multithread programming in Linux OS.

** Showing how to get the thread"s tid and the process"s pid.

** Author:zeickey

** Date:2006/9/16

** Copyright (c) 2006,All Rights Reserved!

*********************************************************************************************/

#include

#include

#include /*getpid()*/

void *create(void *arg)

{

printf("New thread .... /n");

printf("This thread"s id is %u /n", (unsigned int)pthread_self());

printf("The process pid is %d /n",getpid());

return (void *)0;

}

int main(int argc,char *argv[])

{

pthread_t tid;

int error;

printf("Main thread is starting ... /n");

error = pthread_create(&tid, NULL, create, NULL);

if(error)

{

printf("thread is not created ... /n");

return -1;

}

printf("The main process"s pid is %d /n",getpid());

sleep(1);

return 0;

}

编译方法:

gcc -Wall -lpthread pthread_id.c

执行结果:

Main thread is starting ...

The main process"s pid is 3307

New thread ....

This thread"s id is 3086347152

The process pid is 3307

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。

http://www.pinlue.com/style/images/nopic.gif

Linux系统编程36:多线程之线程控制之pthread线程库(线程创建,终止,等待和分离) 文章目录(1)POSIX线程库(2)pthread_create——创建线程A:关于Linux线程的再理解B:线程ID及地址空间布局(3)pthread_exit——线程终止(4)pthread_join——线程等待(5)pthread_detach——线程分离 (1)POSIX线程库 前面说过,在Linux中是用进程模拟线程的,所以就不会用形如fork()这类的系统调用提供给我们用来专门控制线程。所以要实现多线程,就要使用到库函数,这里面比较底层的是POSIX线程库,所以它就是产生的就是用户级别的线程,其 阅读详情

相关推荐

3D Slicer中文教程(三)—数据加载及保存方式

1.打开数据与保存数据 (1)打开数据 ——可以将数据拖拽到3D Slicer应用窗口或者从菜单栏工具栏打开。 ——多种方式加载大量数据。 有关DICOM数据,请参阅DICOM模块文档。 对于几乎所有其他(包括场景),您可以使用添加数据对话框。 有关支持的数据格式的列表,请参阅此列表。 请注意,仅部分支持列出的某些格式。 ——对于一些更复杂的格式(特别是DWI),建议首先使用DICOM到n...

weixin_33676492的博客 5547

pthread 编程

文章目录pthread api创建线程终止线程线程管理栈管理其它互斥量创建与销毁互斥量锁定与解锁互斥量条件变量创建与销毁条件变量等待与通知所有库函数 pthread api 对 pthread api 进行归类, 可以分为四类: 线程管理 直接工作于线程, 如创建, 分离, 加入 (join) 等, 也包括设置或查询线程属性 (joinable, scheduling 等). 互斥量 处理...

ding_yingzi的博客 1193

ROS阿克曼小车避坑指南:TEB Local Planner参数调优实战(附完整配置文件)

本文针对ROS阿克曼底盘机器人,提供了TEB Local Planner参数调优的实战指南。文章深入剖析了阿克曼模型与TEB的协同工作原理,重点讲解了`min_turning_radius`、`cmd_angle_instead_rotvel`等关键参数的设置与调试方法,并分享了性能优化、避障行为调整的实用技巧,旨在帮助开发者避开常见陷阱,实现小车在复杂环境中的稳定、高效导航。

ik6789012的博客 508

C语言多线程基础(pthread)

由于我们没有在主线程中等待我们创建出来的10个线程执行完毕,所以创建出来的子线程可能还没来得及执行,就因为主线程(main函数)执行完毕而终止整个进程,导致子线程没法运行。而且传的是地址,子线程在执行时,i值可能还没更新,所以可能会打印重复的值。但是线程执行的顺序是不固定的,也就是说我们无法预知打印的顺序。根据代码判断程序的输出是不可行的,我们只知道输出的内容,但不知道输出的顺序。使用pthread_join()除了有阻塞线程功能之外,还可以利用其第二个参数,得到线程函数的返回值。

qq_24946843的博客 2629

Abaqus仿真进阶:如何准确计算气动软体机器人的抓取力(Blocking Force分析)

本文详细介绍了使用Abaqus进行气动软体机器人抓取力(Blocking Force)分析的进阶技巧。从材料模型验证、刚性目标物选择到接触对建立和充气加载优化,提供了一套完整的有限元仿真解决方案,帮助工程师准确预测软体执行器的抓取性能。

weixin_42528902的博客 413

单细胞分析避坑指南:SCTransform和Harmony参数设置详解

本文深入解析了单细胞分析中SCTransform标准化与Harmony批次校正的关键参数设置。针对10x Genomics等数据,详细探讨了如何通过调整`vars.to.regress`、`theta`等核心参数,在有效去除技术噪音的同时,避免过度校正以保留关键的生物学差异,从而提升分析结果的可靠性与可解释性。

weixin_29053073的博客 623

C++ 多线程编程(二):pthread的基本使用

pthread中的p是POSIX的缩写,而POSIX是Portable Operating System Interface的缩写,是IEEE为要在各种UNIX操作系统上运行软件,而定义API的一系列互相关联的标准的总称。(Windows环境下无pthread,Linux GCC4.6以下编译需加-pthread编译选项)std::thread是C++11中的新特性,将多线程程序的编写提升到了语言层面,使得编写的多线程程序的可移植性大大提高。

海纳百川,有容乃大。 2万+

基于YOLOv26的道路抛洒物检测系统原理实现

本文提出了一种基于YOLOv26的道路抛洒物智能检测系统,通过深度学习技术实现道路抛洒物的实时检测与分类。系统采用分层架构设计,包含视频采集、目标检测、分类评估和预警处理等模块,能够自动识别轮胎碎片、货物包装、金属零件等多种抛洒物,并根据危险程度分级预警。YOLOv26算法在检测精度和速度上的优势使其特别适合道路监控场景,结合背景建模和运动目标提取技术,有效提高了复杂道路环境下抛洒物的识别率。该系统可集成到现有智能交通监控平台,为道路安全管理提供实时决策支持。

一键难忘的博客 1273

pthread最简单的多线程编程-001

所谓最简单的多线程编程,就是通过pthread_create,pthread_join,pthread_exit 3个api实现线程的创建与终止,而创建的线程只做些简单的工作,如printf一些文字信息。         使用pthread_create,pthread_join,pthread_exit 进行多线程编程的模型如下图所示: 1 pthread_create /

handyhuang的专栏 8715

YOLO26科研升级:OREPA在线重参数化,让模型精度在训练中持续跃升

在目录下,新建AddModules文件夹,将orepa.py放入其中。

LXY_LOVE36的博客 105

3.7 改造模型:为GPT添加一个分类头(Classification Head)

本文介绍如何改造GPT模型用于文本分类任务。主要内容包括: 分类头设计思路:GPT作为语言模型需要添加分类头才能适应分类任务,类似于为语言大师添加裁判功能。 序列表示选择策略: 分析三种常见方法(CLS标记、平均池化、最后词元表示) 推荐使用最后词元表示,因其最能反映GPT的单向信息流特性 代码实现: 构建GPT2ForSequenceClassification类 包含预训练GPT主体和线性分类头 使用attention_mask智能定位句子结尾 通过高级索引提取最后词元特征 该方法通过简单改造使GPT模

yonggeit的博客 2978

linux下多线程(pthread)编程实例,Linux多线程编程实例解析

Linux多线程编程实例解析Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。顺便说一下,Linux 下pthread的实现是通过系统调用clone()来实现的。clone()是 Linux所特有的系统调用,它的使用方式类似fork,关于clone()的详细情况,有兴趣的读...

weixin_32573931的博客 784

UNet改进(54):当医学图像分割遇上频域学习与自监督

本文提出了一种改进U-Net的方法,通过频域增强模块和代理任务模块提升医学图像分割性能。频域增强模块在傅里叶空间对特征图进行可学习的频率调制,重点增强高频细节特征;代理任务模块通过图像重建约束编码器保留关键信息。两个模块协同工作,在仅增加5%参数量的情况下,形成空间域、频域和重建约束三条互补的信息路径。该方法特别适用于需要精细边缘分割的医学图像任务,预期能提升5%-10%的边缘分割精度,在小样本场景效果更显著。部署时可移除代理任务模块,不影响推理效率。未来可探索空间自适应频域调制和更丰富的代理任务设计。

2501_91516851的博客 234

Linux下多线程(pthread)编程实例

Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。顺便说一下,Linux 下pthread的实现是通过系统调用clone()来实现的。clone()是 Linux所特有的系统调用,它的使用方式类似fork,关于clone()的详细情况,有兴趣的读者可以去查看有关文档说明。下

游手好弦 信步涂鸦 2万+

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

转载:Linux下多线程(pthread)编程实例

Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。顺便说一下,Linux 下pthread的实现是通过系统调用clone()来实现的。clone()是 Linux所特有的系统调用,它的使用方式类似fork,关于clone()的详细情况,有兴趣的读者可以去查看有关文...

weixin_30248399的博客 143

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

Linux下c语言多线程编程

引言   线程(thread)技术早在60年代就被提出,但真正应用多线程到操作系统中去,是在80年代中期,solaris是这方面的佼佼者。传统的Unix也支持线程的概念,但是在一个进程(process)中只允许有一个线程,这样多线程就意味着多进程。现在,多   为什么有了进程的概念后,还要再引入线程呢?使用多线程到底有哪些好处?什么的系统应该选用多线程?我们首先必须回答这些问题。   使用...

木牛的博客 7580

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

[原创]手把手教你Linux下的多线程设计--Linux下多线程编程详解(一)

 本文可任意转载,但必须注明作者和出处。【原创】手把手教你Linux下的多线程设计(一)                                      --Linux下多线程编程详解 原创作者:Frozen_socker(冰棍)    E_mail:dlskyfly@163.com         线程也被称为轻权进程(lightweight pro

依然的专栏 3768

Linux多线程编程的基本的函数-pthread_create 例子

http://blog.sina.com.cn/s/blog_4b6068cc0100ix6n.html Linux多线程编程的基本的函数-pthread_create(1) Linux多线程编程的基本的函数-pthread_create(2) Linux多线程编程的基本的函数-pthread_create(3) Linux多线程编程的基本的函数-pthread_create(4) 有一

672

linux下C语言多线程编程实例

学东西,往往实例才是最让人感兴趣的,老是学基础理论,不动手,感觉没有成就感,呵呵。 下面先来一个实例。我们通过创建两个线程来实现对一个数的递加。 或许这个实例没有实际运用的价值,但是稍微改动一下,我们就可以用到其他地方去拉。 下面是我们的代码: /*thr

malei0311 的专栏 427

linux多线程编程学习心得

 网上有一篇《Linux下的多线程编程》介绍的比较详细,细读了一遍,颇有收获!linux下的多线程模型:可用getconf -a | grep GNU_LIBPTHREAD_VERSION查看,我的机器用的是redhat公司研发的NPTL 2.3.4。pthread实现的简单说明:pthread的实现通过系统调用clone()来实现。顺便说一下fork/vfork/clone三者的区别(底层均调用do_fork函数):1.       fork:完全复制,深度拷贝,使用copy-on-write技术。父

hqin6的专栏 4273
上一篇: unix linux下时间结构,unix linux 的时间结构体 -- timestruc_t
下一篇: Linux的文件系统结构是,Linux文件系统结构及主要目录
weixin_30273263
博客等级 码龄9年 43粉丝 83原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值