线程
一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。是操作系统能调度的最小单位。同一进程中的多条线程将共享该进程中的全部系统资源,如虚拟地址空间,文件描述符和信号处理等等。
进程=复习考研英语
线程=背单词、刷阅读、背作文……
线程注意以下几点:
第一个:线程调度规则是由操作系统封装的。(想什么时候背单词或刷阅读由你决定)
第二个:线程之间的切换速度是非常快的,可以认为线程是同时运行的(背单词、刷阅读、背作文可以同时进行)。
第三个:同一个进程下所有线程公用同一块进程空间,这会使得线程的通信变的非常容易
第四个:线程之间会产生相互干扰。因此,学习线程还需要学习,线程的同步和互斥操作。
pthread_create() //创建线程
原型:int pthread_create(pthread_t *thread,const pthread_attr_t *attr,void *(*start_routine)(void *),void *arg)
参数:pthread_t *thread 表示指向新线程的ID指针
const pthread_attr_t *attr 表示线程的属性NULL
void *(*start_routine)(void *) 表示新线程的执行函数,函数指针,指向函数名
void *arg 表示传递给新线程执行函数的参数
pthread_ join() //线程等待函数
互斥锁:一个线程来访问的时候,要加上锁防止其他的线程来访问,实现了资源的独占。
pthread_mutex_init() //动态创建线程互斥锁函数
原型:int pthread_mutex_init(pthread_mutex_t *mutex,const pthread_mutexattr_t *mutexattr);
参数:pthread_mutex_t *mutex --->表示线程互斥锁的指针
const pthread_mutexattr_t *mutexattr 给新创建的线程互斥锁添加属性,缺少属性一般设置为NULL
pthread_mutex_lock() //线程加锁函数
原型:int pthread_mutex_lock(pthread_mutex_t *mutex);
参数:pthread_mutex_t *mutex 表示线程互斥锁的指针---解释:指向要申请互斥锁结构变量的指针
pthread_mutex_unlock //线程互斥锁解锁函数
原型:int pthread_mutex_unlock(pthread_mutex_t *mutex)
参数:pthread_mutex_t *mutex --->表示线程互斥锁的指针
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <signal.h>
4 #include <sys/types.h>
5 #include <stdlib.h>
6 #include <sys/wait.h>
7 #include <sys/stat.h>
8 #include <string.h>
9 #include <fcntl.h>
10 #include <pthread.h>
11
12 void *task(void *arg);
13
14 int i=0;
15 pthread_mutex_t lock;
16
17 int main(int argc,char *argv[]) {
18 pthread_t tid1,tid2,tid3;
19 int ret;
20
21 ret=pthread_mutex_init(&lock,NULL);
22 if(ret!=0){
23 perror("mutex init failed\r\n");
24 return -1;
25 }
26
27 pthread_create(&tid1,NULL,task,(void*)1);
28 pthread_create(&tid2,NULL,task,(void*)2);
29 pthread_create(&tid3,NULL,task,(void*)3);
30
31 pthread_join(tid1,NULL);
32 pthread_join(tid2,NULL);
33 pthread_join(tid3,NULL);
34
35 exit(0);
36
37 }
38
39 void *task(void *arg){
40 while(1){
41 pthread_mutex_lock(&lock);//当进入本线程时,先上锁
42
43 if(i>=20){
44 pthread_mutex_unlock(&lock);
45 break;//计满20时,解锁
46 }
47
48 i++;
49 printf("task%ld:%d\r\n",(intptr_t)(int *)arg,i);
50 sleep(1);
51 pthread_mutex_unlock(&lock);//完成自加后,本线程结束,也解锁
52 sleep(1);
53 }
54 pthread_exit(NULL);
55 }