Linux C 多线程互斥锁及线程同步问题 (二)
来源:互联网 发布:淘宝上传宝贝数据包 编辑:程序博客网 时间:2024/05/15 22:18
需求:主线程创建子线程后等待子线程真正运行。然后主线程向子线程发送同步请求,保证主线程的同步请求信号不丢失。
测试代码:(来自百度,修改。。。)
#include <sys/time.h>#include <pthread.h>#include <unistd.h>#include <stdio.h>#include <string.h>#include <stdlib.h>static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;static int count = 0;struct timeval tv1,tv2,tv3;int timestamp1,timestamp2,timestamp3;/*释放节点内存 */static void cleanup_handler(void *arg){ printf("Cleanup handler of second thread.\n"); free(arg); (void)pthread_mutex_unlock(&mtx);}static void *thread_func(void *arg){int time_fun=0;printf("try lock10........\n");pthread_mutex_lock(&mtx);printf("locked10........\n");pthread_cond_signal(&cond);printf("sended msg to main........\n");pthread_mutex_unlock(&mtx); //解锁 while (1) { printf("wait msg from mian................\n");pthread_cond_wait(&cond, &mtx);printf("get msg from mian.....count:%d.....\n",count); } return 0;}int main(void){int time_create=0; pthread_t tid; int i; pthread_mutexattr_t mutex_attr;pthread_condattr_t cond_attr;pthread_mutexattr_init(&mutex_attr);pthread_condattr_init(&cond_attr);pthread_mutex_init(&mtx, &mutex_attr);pthread_cond_init(&cond, &cond_attr);pthread_condattr_destroy(&cond_attr);pthread_mutexattr_destroy(&mutex_attr); gettimeofday(&tv1, NULL); timestamp1 = tv1.tv_sec * 1000 * 1000 + tv1.tv_usec; pthread_create(&tid, NULL, thread_func, NULL); printf("try lock00...........\n"); pthread_mutex_lock(&mtx); printf("locked00...waiting msg from son.......\n"); pthread_cond_wait(&cond, &mtx); printf("recved msg from son.......\n"); pthread_mutex_unlock(&mtx); //解锁 //usleep(1000); for (i = 0; i < 10; i++) { printf("try lock 02.........\n"); pthread_mutex_lock(&mtx); //需要操作head这个临界资源,先加锁, printf("locked 02.........\n"); count = i; pthread_cond_signal(&cond); printf("try unlock 02.........\n"); pthread_mutex_unlock(&mtx); //解锁 printf("unlocked 02.........\n"); sleep(1); } printf("thread 1 wanna end the cancel thread 2.\n"); pthread_cancel(tid); pthread_join(tid, NULL); printf("All done -- exiting\n"); return 0;}
猜想,主线程创建子线后阻塞等待子线程同步请求,应该可以达到我的需求,事实是第一个主线程的同步请求仍然丢失(偶尔不会丢失)。
暂时就只有休眠等待了修时间增加到1ms才稳定下来。(蓝色)
猜想,提高子线程的优先级可能会解决。等待下次实验吧。
0 0
- Linux C 多线程互斥锁及线程同步问题 (二)
- Linux C 多线程互斥锁及线程同步问题
- MFC 多线程及线程同步 (二)
- C++——多线程编程(二)std::mutex 线程同步、解决资源竞争问题
- 多线程(二)--线程同步
- Java多线程技术研究(二)-线程同步,通信及ThreadLocal
- Linux多线程编程(二)线程同步之条件变量
- Linux多线程及线程间同步
- linux下C语言多线程(三)线程同步
- linux下C语言多线程(三)线程同步
- linux下C语言多线程(三)线程同步
- Linux 多线程编程----线程见同步问题
- Linux C 线程同步实例分析(二)
- linux 线程同步(二)
- MFC 线程创建、多线程、及多线程间的同步问题
- java多线程:线程同步(二)
- java多线程(二)---线程的同步
- 多线程-线程同步问题
- 防备电脑死机实用技巧
- Longest Consecutive Sequence
- 实现Android图片预览的拖拽缩放
- 低成本和高性能MySQL云数据库架构探索
- 教程4:get,post方法与Http协议
- Linux C 多线程互斥锁及线程同步问题 (二)
- UML之部署图
- android代码注入简析
- C# 进程管理
- Struts2 Hibernate Spring 运行流程与部分机制
- 转载Cocos2d-x & NDK常见报错
- 《瞬间之美---WEB页面设计如何让用户心动》读书笔记
- sql 中 with as 用法
- 用Eclipse生成jar文件