多线程同步
来源:互联网 发布:mysql 先排序后去重 编辑:程序博客网 时间:2024/05/16 05:26
</pre><p>一、互斥锁</p><p><pre name="code" class="cpp">#include<stdio.h>#include<pthread.h>#include<stdlib.h>#include<unistd.h>int globle_i = 50;pthread_mutex_t globle_mutex;void* thread_func(){ // pthread_mutex_lock(&globle_mutex); //如果不加锁,仍然可以改变globel_i,所以需要自己控制好锁 while(globle_i != 0) { if( globle_i != 0) { globle_i = globle_i -1; } printf("in new thread globle_i = %d\n", globle_i); usleep(1); } //pthread_mutex_unlock(&globle_mutex); return NULL;}int main(){ pthread_t thread; int res = -1; res = pthread_mutex_init(&globle_mutex, NULL); if(res != 0){ perror("ptherad_mutex_init failed!\n"); exit(EXIT_FAILURE); } res = pthread_create(&thread, NULL, thread_func, NULL); if(res != 0) { perror("ptherad_mutex_init failed!\n"); exit(EXIT_FAILURE); } pthread_mutex_lock(&globle_mutex); while(globle_i != 0) { if( globle_i != 0) { globle_i = globle_i -1; } else{ printf("no more\n"); } printf("in the main thread globle_i=%d\n", globle_i); usleep(1); } pthread_mutex_unlock(&globle_mutex); res = pthread_join(thread, NULL); if(res != 0) { perror("pthread_join failed\n"); exit(EXIT_FAILURE); } printf("thread joined\n"); pthread_mutex_destroy(&globle_mutex); return 0;}
二、条件变量
三、信号量
0 0
- 多线程同步
- 多线程同步
- 多线程同步
- 多线程同步
- 多线程同步
- 多线程同步
- 多线程同步
- 多线程同步
- 同步多线程
- 多线程同步
- 多线程同步
- 多线程、同步
- 多线程同步
- 多线程同步
- 多线程同步
- 多线程同步
- 多线程同步
- 多线程同步
- iOS生成开发者证书和发布者证书(新手可看)
- label根据填充的内容自适应
- 【SSH (九)】Eclipse使用hibernate插件反向生成实体类和映射文件
- 公司请你来干嘛?
- 【2016更新】修改Host文件,让你的Google跑起来 2016 Google hosts(2016-2-29更新hosts文件)
- 多线程同步
- [Unity插件]DOTween(2)
- lightoj 1030 Discovering Gold 概率dp求期望
- 类加载器以及双亲委派模型介绍
- SpringMVC访问静态资源的三种方式
- 设计模式学习笔记——外观模式
- C语言构建WEB管理系统(五):CGI实现上传文件
- JSTL (jsp标准标签库)
- 【leetcode】【198】House Robber