昨日家中断网,除此类突发情况和周末外,原则上不中断。
线程
学计算机原理必须听到的一句话:线程是操作系统运算调度的最小单位。但个人觉得这句话说的不太严谨,严格意义上来说,操作系统运算调度的最小单位应该是指令。线程只能视为一系列运算指令构成的最小调度单元。
同一进程可以拥有多条线程,线程之间共享该进程中的全部系统资源,如虚拟地址空间,文件描述符和信号处理等等。但同一进程中的多个线程有各自的调用栈(call stack),自己的寄存器环境(register context),自己的线程本地存储(thread-local storage)。
多线程可以提高程序在多核机器上某些任务的处理性能。如果采用多进程的方式,进程间通信需要通过管道等方式,数据在用户空间和内核空间频繁切换,开销很大。而多线程因为可以使用共享的全局变量,所以通信(数据交换)非常高效。
Unix系统中,C语言线程相关主要函数定义在/usr/include/pthread.h
头文件中。其中最常用的主要有以下函数:
1 | //创建线程 |
多线程
多线程样例:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
/*
* test.c
* 编译:gcc -m32 -lpthread -o test test.c
* 运行: ./test
*/
void print_msg(int);
void main(){
pthread_t threads[8];
void * func = &print_msg;
int i=0;
for(i=0;i<4;i++){
printf("Init thread %d\n",i);
pthread_create(&threads[i],NULL,func,(void *)i);
}
for(i=0;i<4;i++){
pthread_join((long unsigned int)&threads[i],NULL);
}
pthread_exit(NULL);
}
void print_msg(int sec){
printf("Thread-%d Start.\n", sec);
sleep(sec);
printf("Thread-%d Done.\n", sec);
}
/*
运行结果:
Init thread 0
Init thread 1
Init thread 2
Init thread 3
Thread-3 Start.
Thread-1 Start.
Thread-0 Start.
Thread-2 Start.
Thread-0 Done.
Thread-1 Done.
Thread-2 Done.
Thread-3 Done.
*/
今晚记录的内容有点草率,一些详细的用法未能完全梳理,以后如果有机会再追加。