网络编程系列之二 互斥量
来源:互联网 发布:蒙泰打印机端口在哪里 编辑:程序博客网 时间:2024/06/06 23:53
//首先线程同步有几种方式, 互斥量,信号量,条件//互斥量的目的是保护一段临界区,而不是用来调整主线程和所创建线程的执行顺序//用在当一个线程的访问临界区时会对另一个线程的访问有影响,所以使用互斥锁//另外互斥锁的初始化时,没有设置其属性,这样的话线程无法递归加锁,需要递归的时候就要设置互斥锁的属性,使用pthread_mutexattr_t#include <stdio.h>#include <stdlib.h>#include <pthread.h>int *fun(int *i);//创建线程锁, 本例子创建线程锁意义不大,只是用来说明其用法pthread_mutex_t mymutex; //在main函数外创建,这样线程函数才能访问到,初始化在main中就可以了int main(){ int res; void *pthread_result; //用来获取线程的返回值 int i = 0; res = pthread_mutex_init(&mymutex,NULL); if(0 != res) { perror("mutex init error\n"); } //创建新线程 pthread_t mythread; res = pthread_create(&mythread, NULL, fun, &i); //第三个和第四个属性可是是任何类型的指针 if(0 != res) { perror("create thread error\n"); } int x_main = 0; pthread_mutex_lock(&mymutex); for(;x_main< 500;x_main++) printf("now number is %d\n",i++); pthread_mutex_unlock(&mymutex); //等待线程结束 res = pthread_join(mythread, &pthread_result);// 一种观点认为, 这个函数会导致主线程阻塞 if(0 != res) { perror("join failed\n"); } //锁使用完成后, 释放锁资源 pthread_mutex_destroy(&mymutex); printf("the number of i is: %d\n", i); printf("thread return: %s\n",pthread_result); return 0;}//int *fun(int *i){ int x_thread = 0; pthread_mutex_lock(&mymutex); for(;x_thread< 500;x_thread++) printf("now number is %d\n",(*i)++); pthread_mutex_unlock(&mymutex); pthread_exit("the thread has exit");}
0 0
- 网络编程系列之二 互斥量
- 网络编程之二
- Qt网络编程之二
- Qt网络编程之二
- 09.网络编程之二
- Linux网络编程之二
- 【java网络编程】之二
- C#网络编程系列文章(二)之Socket实现同步TCP服务器
- C#网络编程系列文章(二)之Socket实现同步TCP服务器
- 高级编程之网络编程(二)
- 网络编程系列二--最简单的网络程序
- 技术系列之 网络模型(二)
- 技术系列之 网络模型(二)
- 网络编程系列之三 信号量
- 网络编程系列之四 条件
- 网络编程系列之九 getopt()函数
- Java总结系列之网络编程
- javase重新开始系列之网络编程
- SDNU 1168.FBI树【NOIP 2004 普及组】【不建树】【7月28】
- android ListView 几个重要属性和使用小技巧
- ionic的tabs学习
- UVA 10061 How many zeros and how many digits?
- 暑假- Trie树-(D - Phone List)
- 网络编程系列之二 互斥量
- hdu 2734(Quicksum)
- 三星通话记录数据库存放地址
- sublime text 3 快捷键大全以及配置编译环境
- 捋捋所遇见的WdatePicker插件的用法
- Apache Shiro 使用手册(四)Realm 实现
- hdoj 2043密码
- Linux网络编程select模型的实现
- MFC中获得对话框控件相对于父窗口的位置