首页/新闻资讯/正文详情

Linux多线程开发

发布时间:2026/11/29 2:48:25 来源:云帆数科 栏目:资讯中心
Linux多线程开发
线程概述线程创建一般情况下main函数所在的线程我们称之为主线程其余创建的线程称之为子线程程序中默认只有一个进程fork()函数调用2个进程程序中默认只有一个线程pthread_create()函数调用2个线程#include pthread.hint pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);功能创建一个子线程参数- thread传出参数线程创建成功后子线程的线程ID被写到该变量中- attr设置线程的属性一般使用默认值NULL- start_routine函数指针这个函数是子线程需要处理的逻辑代码- arg给第三个参数使用传参返回值成功0失败返回错误号这个错误号和之前errno不太一样获取错误号信息char *strerror(int errnum); //#include string.h#include stdio.h #include pthread.h #include string.h #include unistd.h void *callback(void *arg) { printf(child thread...\n); printf(arg value :%d\n,*(int *)arg); return NULL; } int main() { pthread_t tid; int num 10; //创建一个子线程 int ret pthread_create(tid,NULL,callback,(void*)num); if(ret ! 0) { char *errstr strerror(ret); printf(error : %s\n,errstr); } for(int i 0;i 5;i ) { printf(%d\n,i); } sleep(1); return 0; }线程终止#include pthread.hvoid pthread_exit(void *retval);功能终止一个线程在哪个线程中调用就表示终止哪个线程参数reval需要传递一个指针作为一个返回值可以在pthread_join()中pthread_t pthread_self(void);功能获取当前的线程的线程IDint pthread_equal(pthread_t t1,pthread_t t2);功能比较两个线程ID是否相等不同的操作系统pthread_t类型的实现有的是无符号的长整型有的是使用结构体去实现的#include stdio.h #include pthread.h #include string.h void *callback(void *arg) { printf(child thread id:%ld\n,pthread_self()); return NULL; //pthread_exit(NULL) } int main() { //创建一个子线程 pthread_t tid; int ret pthread_create(tid,NULL,callback,NULL); if(ret ! 0) { char *errstr strerror(ret); printf(error:%s\n,errstr); } //主线程 for(int i 0;i 5;i ) { printf(%d\n,i); } printf(tid :%ld ,main thread id:%ld\n,tid,pthread_self()); //让主线程退出 pthread_exit(NULL); return 0; }#include pthread.hint pthread_join(pthread_t thread, void **retval);功能和一个已经终止的线程进行连接回收子线程的资源这个函数是阻塞函数调用一次只能回收一个子线程一般在主线程中使用参数thread需要回收的子线程的IDretval接收子线程退出时的返回值返回值0成功非0失败返回的错误号#include stdio.h #include pthread.h #include string.h #include unistd.h int value 10; void *callback(void *arg) { printf(child thread id:%ld\n,pthread_self()); //sleep(3); pthread_exit((void*)value); } int main() { //创建一个子线程 pthread_t tid; int ret pthread_create(tid,NULL,callback,NULL); if(ret ! 0) { char *errstr strerror(ret); printf(error:%s\n,errstr); } //主线程 for(int i 0;i 5;i ) { printf(%d\n,i); } printf(tid :%ld ,main thread id:%ld\n,tid,pthread_self()); //主线程调用pthread_join()回收子线程的资源 int *thread_retval; ret pthread_join(tid,(void **)thread_retval);//不需要传参则可以写NULL if(ret ! 0) { char *errstr strerror(ret); printf(error:%s\n,errstr); } printf(exit data : %d\n,*thread_retval); printf(回收子线程资源成功\n); //让主线程退出 pthread_exit(NULL); return 0; }线程分离#include pthread.hint pthread_detach(pthread_t thread);功能分离一个线程被分离的线程在终止的时候会自动释放资源返回给系统1、不能多次分离会产生不可预料的行为2、不能用pthread_join()连接一个已经分离的线程操作会报错参数需要分离的线程ID返回值成功0失败返回错误号#include stdio.h #include pthread.h #include string.h #include unistd.h void *callback(void *arg) { printf(child thread id : %ld\n,pthread_self()); return NULL; } int main() { pthread_t tid; int ret pthread_create(tid,NULL,callback,NULL); if(ret ! 0) { char *errstr strerror(ret); printf(error1:%s\n,errstr); } //输出主线程和子线程的id printf(tid : %ld,main thread id:%ld\n,tid,pthread_self()); //设置子线程分离,子线程分离后子线程结束时对应的资源就不需要主线程释放 ret pthread_detach(tid); if(ret ! 0) { char *errstr strerror(ret); printf(error2:%s\n,errstr); } pthread_exit(NULL); return 0; }线程取消#include pthread.hint pthread_cancel(pthread_t thread);功能取消线程让线程终止取消线程可以终止某个线程的运行但是并不是立马终止而是当子线程执行到一个取消点线程才会终止取消点系统规定好的一些系统调用我们可以粗略的理解为从用户区到内核区的切换这个位置称为取消点#include stdio.h #include pthread.h #include string.h #include unistd.h void *callback(void *arg) { printf(child thread id : %ld\n,pthread_self()); for(int i 0;i 5;i ) { printf(child :%d\n,i); } return NULL; } int main() { pthread_t tid; int ret pthread_create(tid,NULL,callback,NULL); if(ret ! 0) { char *errstr strerror(ret); printf(error1:%s\n,errstr); } //输出主线程和子线程的id printf(tid : %ld,main thread id:%ld\n,tid,pthread_self()); //取消线程 pthread_cancel(tid); for(int i 0;i 5;i ) { printf(%d\n,i); } pthread_exit(NULL); return 0; }线程属性int pthread_attr_init(pthread_attr_t *attr);-初始化线程属性变量int pthread_attr_destroy(pthread_attr_t *attr);- 释放线程属性的资源int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate);- 获取线程分离的状态属性int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);- 设置线程分离的状态属性#include stdio.h #include pthread.h #include string.h #include unistd.h void *callback(void *arg) { printf(child thread id : %ld\n,pthread_self()); return NULL; } int main() { //创建一个线程属性变量 pthread_attr_t attr; //初始化属性变量 pthread_attr_init(attr); //设置属性 pthread_attr_setdetachstate(attr,PTHREAD_CREATE_DETACHED); pthread_t tid; int ret pthread_create(tid,attr,callback,NULL); if(ret ! 0) { char *errstr strerror(ret); printf(error1:%s\n,errstr); } //输出主线程和子线程的id printf(tid : %ld,main thread id:%ld\n,tid,pthread_self()); //获取线程栈的大小 size_t size; pthread_attr_getstacksize(attr,size); printf(Thread stack size:%ld\n,size); //释放线程属性资源 pthread_attr_destroy(attr); pthread_exit(NULL); return 0; }线程同步互斥量/互斥锁互斥量的类型 pthread_mutex_t◼ int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);- 功能初始化互斥量- 参数-mutex需要初始化的互斥量变量-attr互斥量相关的属性NULL- restrictC语言的修饰符被修饰的指针不能由另外的一个指针进行操作◼ int pthread_mutex_destroy(pthread_mutex_t *mutex);- 功能释放互斥量的资源◼ int pthread_mutex_lock(pthread_mutex_t *mutex);- 功能加锁如果有一个线程加锁那么其他线程只能阻塞等待◼ int pthread_mutex_trylock(pthread_mutex_t *mutex);- 功能尝试加锁如果加锁失败不会阻塞会直接返回◼ int pthread_mutex_unlock(pthread_mutex_t *mutex);- 功能解锁死锁多线程多锁的情况#include stdio.h #include pthread.h #include unistd.h //创建2个互斥量 pthread_mutex_t mutex1,mutex2; void *worka(void *arg) { pthread_mutex_lock(mutex1); sleep(1); pthread_mutex_lock(mutex2); printf(worka...\n); pthread_mutex_unlock(mutex2); pthread_mutex_unlock(mutex1); return NULL; } void *workb(void *arg) { pthread_mutex_lock(mutex2); sleep(1); pthread_mutex_lock(mutex1); printf(workb...\n); pthread_mutex_unlock(mutex1); pthread_mutex_unlock(mutex2); return NULL; } int main() { //初始化互斥量 pthread_mutex_init(mutex1,NULL); pthread_mutex_init(mutex2,NULL); //创建2个子线程 pthread_t tid1,tid2; pthread_create(tid1,NULL,worka,NULL); pthread_create(tid2,NULL,workb,NULL); //回收子线程资源 pthread_join(tid1,NULL); pthread_join(tid2,NULL); //释放互斥量资源 pthread_mutex_destroy(mutex1); pthread_mutex_destroy(mutex2); return 0; }读写锁◼ 读写锁的类型 pthread_rwlock_t◼ int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);◼ int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);◼ int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);◼ int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);◼ int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);◼ int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);◼ int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);#include stdio.h #include pthread.h #include unistd.h /* 案例8个线程操作同一个全局变量 3个线程不定时写这个全局变量5个线程不定时的读这个全局变量 */ int num 1; pthread_rwlock_t rwlock; void *writeNum(void *arg) { while (1) { pthread_rwlock_wrlock(rwlock); num ; printf(write,tid:%ld,num:%d\n,pthread_self(),num); pthread_rwlock_unlock(rwlock); usleep(100); } return NULL; } void *readNum(void *arg) { while(1) { pthread_rwlock_rdlock(rwlock); printf(read,tid:%ld,num : %d\n,pthread_self(),num); pthread_rwlock_unlock(rwlock); usleep(100); } return NULL; } int main() { pthread_rwlock_init(rwlock,NULL); //创建3个写线程5个读线程 pthread_t wtids[3],rtids[5]; for(int i 0;i 3;i ) { pthread_create(wtids[i],NULL,writeNum,NULL); } for(int i 0;i 5;i ) { pthread_create(rtids[i],NULL,readNum,NULL); } //设置线程分离 for(int i 0;i 3;i ) { pthread_detach(wtids[i]); } for(int i 0;i 5;i ) { pthread_detach(rtids[i]); } pthread_exit(NULL); pthread_rwlock_destroy(rwlock); return 0; }生产者消费者模型条件变量与互斥锁一起用◼ 条件变量的类型 pthread_cond_t◼ int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);功能初始化条件变量◼ int pthread_cond_destroy(pthread_cond_t *cond);功能释放条件变量◼ int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);功能阻塞函数调用该函数线程会阻塞当这个函数调用阻塞的时候会对互斥锁进程解锁当不阻塞的时候继续向下执行会重新加锁◼ int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);功能设置等待多少时间调用这个函数线程会阻塞直到指定时间结束◼ int pthread_cond_signal(pthread_cond_t *cond);功能唤醒一个或者多个等待线程◼ int pthread_cond_broadcast(pthread_cond_t *cond);功能唤醒所有等待的线程/* 生产者消费者模型粗略的版本 */ #include stdio.h #include pthread.h #include stdlib.h #include unistd.h struct Node{ int num; struct Node *next; }; pthread_mutex_t mutex; pthread_cond_t cond; //头结点 struct Node *head NULL; void *producer(void *arg) { //不断创建新的结点添加到链表中 while(1) { pthread_mutex_lock(mutex); struct Node *newNode (struct Node*)malloc(sizeof(struct Node)); newNode-next head; head newNode; newNode-num rand() % 1000; printf(add node,num:%d,tid:%ld\n,newNode-num,pthread_self()); //只要生产一个就通知消费者消费 pthread_cond_signal(cond); pthread_mutex_unlock(mutex); usleep(100); } return NULL; } void *customer(void *arg) { while(1) { pthread_mutex_lock(mutex); //判断是否有数据 if(head ! NULL) { //保存头结点的指针 struct Node *tmp head; head head-next; printf(del node,num : %d,tid :%ld\n,tmp-num,pthread_self()); free(tmp); pthread_mutex_unlock(mutex); usleep(100); } else{ //没有数据需要等待 pthread_cond_wait(cond,mutex); pthread_mutex_unlock(mutex); } } return NULL; } int main() { //创建5个生产者线程和5个消费者线程 pthread_mutex_init(mutex,NULL); pthread_cond_init(cond,NULL); pthread_t ptids[5],ctids[5]; for(int i 0;i 5;i ) { pthread_create(ptids[i],NULL,producer,NULL); pthread_create(ctids[i],NULL,customer,NULL); } for(int i 0;i 5;i ) { pthread_detach(ptids[i]); pthread_detach(ctids[i]); } while(1) { sleep(10); } pthread_mutex_destroy(mutex); pthread_cond_destroy(cond); pthread_exit(NULL); return 0; }信号量#include semaphore.h◼ 信号量的类型 sem_t◼ int sem_init(sem_t *sem, int pshared, unsigned int value);功能初始化信号量参数sem信号量psshared0用在线程间 非0用在进程间value信号量中的值◼ int sem_destroy(sem_t *sem);功能释放资源◼ int sem_wait(sem_t *sem);功能对信号量加锁调用一次对这个信号量的值-1如果值为0就阻塞◼ int sem_trywait(sem_t *sem);功能尝试等待◼ int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);◼ int sem_post(sem_t *sem);功能对信号量解锁调用一次对信号量的值1◼ int sem_getvalue(sem_t *sem, int *sval);/* 生产者消费者模型粗略的版本 */ #include stdio.h #include pthread.h #include stdlib.h #include unistd.h #include semaphore.h struct Node{ int num; struct Node *next; }; pthread_mutex_t mutex; //创建两个信号量 sem_t psem; sem_t csem; //头结点 struct Node *head NULL; void *producer(void *arg) { //不断创建新的结点添加到链表中 while(1) { sem_wait(psem); pthread_mutex_lock(mutex); struct Node *newNode (struct Node*)malloc(sizeof(struct Node)); newNode-next head; head newNode; newNode-num rand() % 1000; printf(add node,num:%d,tid:%ld\n,newNode-num,pthread_self()); pthread_mutex_unlock(mutex); sem_post(csem); usleep(100); } return NULL; } void *customer(void *arg) { while(1) { sem_wait(csem); pthread_mutex_lock(mutex); //判断是否有数据 //保存头结点的指针 struct Node *tmp head; head head-next; printf(del node,num : %d,tid :%ld\n,tmp-num,pthread_self()); free(tmp); pthread_mutex_unlock(mutex); sem_post(psem); usleep(100); } return NULL; } int main() { pthread_mutex_init(mutex,NULL); sem_init(psem,0,8); sem_init(csem,0,0); //创建5个生产者线程和5个消费者线程 pthread_mutex_init(mutex,NULL); pthread_t ptids[5],ctids[5]; for(int i 0;i 5;i ) { pthread_create(ptids[i],NULL,producer,NULL); pthread_create(ctids[i],NULL,customer,NULL); } for(int i 0;i 5;i ) { pthread_detach(ptids[i]); pthread_detach(ctids[i]); } while(1) { sleep(10); } pthread_mutex_destroy(mutex); pthread_exit(NULL); return 0; }

相关推荐

LogicTrack: Auditing Reasoning Trajectories of Large Language Models with Formal Logic Solvers 论文总结与
LogicTrack: Auditing Reasoning Trajectories of Large Language Models with Formal Logic Solvers 论文总结与

# LogicTrack: Auditing Reasoning Trajectories of Large Language Models with Formal Logic Solvers 论文总结与翻译> 论文arXiv链接:https://arxiv.org/abs/2609.21492 ## 一、论文主要内容Chain‑of‑Thought(思维链CoT)能够提升大语言模型推理能力,但现有优化大多… · 2026/11/29 2:48:24

Beyond Single‑Model Injection 论文总结
Beyond Single‑Model Injection 论文总结

> 说明:arXiv摘要页面只公开**Abstract**,未直接提供 Introduction、Conclusion 完整文本;公开的网页摘要仅能拿到Abstract原文。下面完成:文章概要、创新点、Abstract中英对照;并标注Introduction/Conclusion获取方式。输出完整Markdown文档。 # Beyond Single‑Mode… · 2026/11/29 2:48:23

语音生产线专用配音校对工具:精准检测与修正发音错误
语音生产线专用配音校对工具:精准检测与修正发音错误

1. 这不是“听一遍改一遍”的简单工具,而是语音产线里真正能卡住质量关口的校对引擎最近在给几家做有声书批量生产的团队做技术咨询时,反复被问到一个问题:为什么我们投入了大量人力做配音质检,错误率还是压不下来?翻看… · 2026/11/16 21:47:49

章丘区考电工证在哪里 怎么考不踩坑 郑州报考避坑指南
章丘区考电工证在哪里 怎么考不踩坑 郑州报考避坑指南

章丘区考电工证在哪里 怎么考不踩坑 郑州报考避坑指南 怕考不过白交培训费?别慌,这波你必须知道的电工证报考干货来了。在章丘区考电工证,选对地方和培训机构,是顺利取证的关键。但很多人在郑州等地报考时,一不小心就掉进培训机构的坑里,花了几千块培… · 2026/11/29 2:47:30

高低压电工证过期了不知道怎么复审?查高低压电工证上岗必备全攻略
高低压电工证过期了不知道怎么复审?查高低压电工证上岗必备全攻略

高低压电工证过期了不知道怎么复审?查高低压电工证上岗必备全攻略 证书过期了不知道怎么复审延期?你不是一个人。最近很多低压、高压电工证持有者都在问这个问题,尤其是一线电工从业者,证书一旦过期,就等于失去了工作的“通行证”。今天咱们就来聊聊【查… · 2026/11/29 2:47:30

漳州龙海电工证培训多久拿证?学历不高也能轻松上手
漳州龙海电工证培训多久拿证?学历不高也能轻松上手

漳州龙海电工证培训多久拿证?学历不高也能轻松上手 你是不是也担心自己学历不高,怕报不了名?其实,漳州龙海电工证培训 多久拿证… · 2026/11/29 2:47:30

廊坊特种工培训机构真实经历:怕考不过白交培训费?这几点帮你避坑
廊坊特种工培训机构真实经历:怕考不过白交培训费?这几点帮你避坑

廊坊特种工培训机构真实经历:怕考不过白交培训费?这几点帮你避坑 你是不是也担心,花了几千块报名了廊坊特种工培训机构,最后考试还是没过,钱打水漂?我身边就有人因为没选对机构,考试挂科后维权困难,白白损失了几千块。今天咱们就从濮阳初次报考人员的… · 2026/11/29 2:47:30

重庆渝北电工证报名怕被中介坑?听听真实经历怎么说
重庆渝北电工证报名怕被中介坑?听听真实经历怎么说

重庆渝北电工证报名怕被中介坑?听听真实经历怎么说 你是不是也和我一样,第一次听说要考电工证,就被各种培训机构搞得一头雾水?重庆渝北电工证报名到底去哪?中介会不会坑钱?别急,今天我以一名漯河培训机构学员的身份,来跟你聊聊我的 真实经历… · 2026/11/29 2:46:29

民权县特种工证在哪办怎么报名?学历不高怕报不上名?别慌,教你一步到位!
民权县特种工证在哪办怎么报名?学历不高怕报不上名?别慌,教你一步到位!

民权县特种工证在哪办怎么报名?学历不高怕报不上名?别慌,教你一步到位! 你是不是也觉得学历不高,连特种工证都报不上名?别急,今天就告诉你, 民权县特种工证在哪办怎么报名 ,怎么用最短的时间、最低的门槛拿下一张能赚钱的证。… · 2026/11/29 2:46:29

工地太忙根本没时间复习考试?考电工证昆明千万别踩坑
工地太忙根本没时间复习考试?考电工证昆明千万别踩坑

工地太忙根本没时间复习考试?考电工证昆明千万别踩坑 工地太忙根本没时间复习考试,这是很多一线施工人员的真实写照。尤其在昆明这样的工程大市,特种作业操作证的需求量不断攀升,但很多工人因为工作节奏快、任务紧,连最基本的考试复习时间都挤不出来,结… · 2026/11/29 0:00:07

电工证线下报名地点怎么找?全国通用证书怎么考?
电工证线下报名地点怎么找?全国通用证书怎么考?

电工证线下报名地点怎么找?全国通用证书怎么考? 你是不是正在找电工证线下报名地点,想着赶紧考个证上岗?别急,现在就告诉你怎么操作。电工证是特种作业操作证的一种, 全国通用… · 2026/11/29 0:00:07

电工证 联网如何操作?官方报名入口全攻略
电工证 联网如何操作?官方报名入口全攻略

电工证 联网如何操作?官方报名入口全攻略 证书过期了不知道怎么复审延期?很多电工朋友在工作中遇到过这样的尴尬,尤其是在一线操作岗位,证件一旦过期,就面临停岗、扣工资甚至被清退的风险。而“电工证… · 2026/11/29 0:00:07

工地太忙根本没时间复习考试?考电工证昆明千万别踩坑
工地太忙根本没时间复习考试?考电工证昆明千万别踩坑

工地太忙根本没时间复习考试?考电工证昆明千万别踩坑 工地太忙根本没时间复习考试,这是很多一线施工人员的真实写照。尤其在昆明这样的工程大市,特种作业操作证的需求量不断攀升,但很多工人因为工作节奏快、任务紧,连最基本的考试复习时间都挤不出来,结… · 2026/11/29 0:00:07

电工证线下报名地点怎么找?全国通用证书怎么考?
电工证线下报名地点怎么找?全国通用证书怎么考?

电工证线下报名地点怎么找?全国通用证书怎么考? 你是不是正在找电工证线下报名地点,想着赶紧考个证上岗?别急,现在就告诉你怎么操作。电工证是特种作业操作证的一种, 全国通用… · 2026/11/29 0:00:07

电工证 联网如何操作?官方报名入口全攻略
电工证 联网如何操作?官方报名入口全攻略

电工证 联网如何操作?官方报名入口全攻略 证书过期了不知道怎么复审延期?很多电工朋友在工作中遇到过这样的尴尬,尤其是在一线操作岗位,证件一旦过期,就面临停岗、扣工资甚至被清退的风险。而“电工证… · 2026/11/29 0:00:07

双极步进电机控制实战:DRV8818PWPR与PIC18F86K22驱动调试
双极步进电机控制实战:DRV8818PWPR与PIC18F86K22驱动调试

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/11/28 0:39:37

STM32F207ZG + DRV8818PWPR 步进电机驱动实战解析
STM32F207ZG + DRV8818PWPR 步进电机驱动实战解析

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/11/28 17:57:33

DRV8818PWPR+dsPIC30F4013工业级双极步进电机控制方案
DRV8818PWPR+dsPIC30F4013工业级双极步进电机控制方案

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/11/28 22:22:49

了解更多?预约专属演示

我们的顾问将为您一对一讲解产品与方案

企业微信二维码