linux 多线程demo pthread
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | /*t01_testthread.cpp*/ #include<stdlib.h> #include<stdio.h> #include<unistd.h> #include<pthread.h> /* 看到这里可能会有点疑问,为何除了条件变量还需要一个互斥对象呢?等待时为什么需要条件变量和互斥对象共同生效呢? 条件变量的操作也需要达到线程安全的要求,因此需要互斥对象来进行保证。避免两个线程同时操作条件变量引发问题。而通过查阅pthread_cond_wait()的相关资料可知, 当程序运行到pthread_cond_wait()时,会将互斥对象锁释放,以便生产者能够顺利唤醒。 而在消费者被成功唤醒,pthread_cond_wait()等待完成后,互斥对象会被重新上锁直到手动释放。 程序流程: 1 main createpthread,ThreadFunc函数会在一个不确定时间开始执行(不知道啥时间抢占到cpu) 2 main 休眠2000ms,等待 子线程开始运行, 3 子线程得到cpu,开始先抢占锁 pthread_mutex_lock ,然后执行 pthread_cond_wait 再释放锁,告知其他线程子线程已经准备好接收信号了 4 主线程休眠2000ms后, pthread_mutex_lock 抢占锁,执行 pthread_cond_signal ,告知对应,有个唤醒消息,然后执行pthread_mutex_unlock释放锁 5 子线程收到唤醒消息,然后开始抢占锁(内部自动进行) 然后开始执行处理逻辑,执行完毕,释放锁,一次逻辑结束 6 子线程如果想继续进行,需要获取锁pthread_mutex_lock,并进行到pthread_cond_wait释放锁 编译(嵌入式): aarch64-linux-gnu-gcc -o t01_testthread t01_testthread.c -lpthread 或者: gcc -o t01_testthread t01_testthread.c -lpthread */ pthread_cond_t cond=PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex; void *ThreadFunc( void *arg) { while (1){ pthread_mutex_lock(&mutex); /*此处等待唤醒*/ printf ( "Thread sleeping...\n" ); pthread_cond_wait(&cond, &mutex); /*唤醒成功*/ printf ( "Thread awakened!...\n" ); usleep(500000); //handle 500ms pthread_mutex_unlock(&mutex); printf ( "Thread unlock!...\n" ); } return NULL; } int main( void ) { printf ( "pthread v1.0.1 ...\n" ); pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); pthread_t tid; pthread_create(&tid, NULL, ThreadFunc, NULL); /*等待5秒再唤醒,方便观察*/ printf ( "main sleeping...\n" ); usleep(2000000); pthread_mutex_lock(&mutex); /*唤醒*/ printf ( "main lock...\n" ); pthread_cond_signal(&cond); printf ( "main signal...\n" ); pthread_mutex_unlock(&mutex); printf ( "main unlock...\n" ); usleep(1000000); //handle 1000ms printf ( "main finished...\n" ); return 0; } |
//今天发现的一个c的库 jingweizhanghuai/Morn: Morn是一个C语言的基础工具和基础算法库,包括数据结构、图像处理、音频处理、机器学习等,具有简单、通用、高效的特点。 (github.com)
//
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构