Linux下多线程编程
来源:互联网 发布:人工智能利大于弊辩论 编辑:程序博客网 时间:2024/05/20 19:19
http://fanqiang.chinaunix.net/a4/b8/20010811/0905001105.html
为什么有了进程的概念后,还要再引入线程呢?使用多线程到底有哪些好处?什么的系统应该选用多线程?
使用多线程的理由之一是和进程相比,它是一种非常"节俭"的多任务操作方式。
使用多线程的理由之二是线程间方便的通信机制。
1) 提高应用程序响应。
2) 使多CPU系统更加有效。
3) 改善程序结构。
/* example.c*/#include <stdio.h>#include <pthread.h>void thread(void){int i;for(i=0;i<3;i++)printf("This is a pthread.\n");}int main(void){pthread_t id;int i,ret;ret=pthread_create(&id,NULL,(void *) thread,NULL);if(ret!=0){printf ("Create pthread error!\n");exit (1);}for(i=0;i<3;i++)printf("This is the main process.\n");pthread_join(id,NULL);return (0);}我们编译此程序:gcc example1.c -lpthread -o example1运行example1,我们得到如下结果:This is the main process.This is a pthread.This is the main process.This is the main process.This is a pthread.This is a pthread.再次运行,我们可能得到如下结果:This is a pthread.This is the main process.This is a pthread.This is the main process.This is a pthread.This is the main process.
修改线程的属性
属性对象主要包括是否绑定、是否分离、堆栈地址、堆栈大小、优先级。默认的属性为非绑定、非分离、缺省1M的堆栈、与父进程同样级别的优先级。
轻进程可以理解为内核线程,系统对线程资源的分配、对线程的控制是通过轻进程来实现的。
绑定状况下,则顾名思义,即某个线程固定的"绑"在一个轻进程之上。pthread_attr_init(&attr);thread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
分离线程它没有被其他的线程所等待,自己运行结束了,线程也就终止了,马上释放系统资源。pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate
线程的优先级,它存放在结构sched_param中。用函数pthread_attr_getschedparam和函数pthread_attr_setschedparam进行存放
线程的数据处理
1 线程数据
每个线程数据创建一个键,在不同的线程里,这个键代表的数据是不同的,在同一个线程里,它代表同样的数据内容。pthread_keycreate
2 互斥锁
互斥锁用来保证一段时间内只有一个线程在执行一段代码。
pthread_mutex_init
pthread_mutexattr_setpshared
pthread_mutexattr_settype
pthread_mutex_lock
pthread_mutex_lock
pthread_mutex_trylock
3 条件变量
条件变量被用来进行线承间的同步
pthread_cond_init
pthread_cond_ destroy
pthread_cond_timedwait
pthread_cond_broadcast
4 信号量
信号量本质上是一个非负的整数计数器,它被用来控制对公共资源的访问。
sem_post
sem_wait
sem_trywait
pthread_mutex_trylock
sem_init
- linux下多线程编程
- linux下多线程编程
- LINUX 下多线程编程
- Linux下多线程编程
- Linux下多线程编程
- linux 下多线程编程
- linux下多线程编程
- linux下多线程编程
- LInux 下多线程编程
- Linux下多线程编程
- Linux下多线程编程
- Linux下多线程编程
- Linux下多线程编程
- linux下多线程编程
- Linux下多线程编程
- linux下多线程编程
- Linux下多线程编程
- linux下多线程编程
- 复用jquery的ajax调用模块
- 软件过程管理的最佳实践
- iOS-xcode内存泄露 检查静态/动态
- Struts2+Spring+iBatis+Jquery的框架搭建二
- Linux下 NFS 服务器配置
- Linux下多线程编程
- 将shell脚本用到实处
- 欧拉计划第一题(改进版)
- c++的一些知识
- Inventory Transfer To GL(11i)
- 关于PCA+KNN下的人脸识别
- DNS错误怎么办?专家教你怎么解决 DNS错误
- ActionContext和ServletActionContext小结
- c++inherit