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

 

 

 

 

 

 

 

 

 

 

原创粉丝点击