线程(thread)是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。
C语言编程中,基于POSIX thread libraries可以实现多线程并发式编程。
The POSIX thread libraries are a standards based thread API for C/C++. It allows one to spawn a new concurrent process flow. It is most effective on multi-processor or multi-core systems where the process flow can be scheduled to run on another processor thus gaining speed through parallel or distributed processing.
先来看一个简单的例子。下面的代码中,我们定义了一个字符串 “AbaCaZaBBC”,然后编程统计字符串中大写字母的个数。特别地,这里我们将使用多线程的方式来执行程序。具体来说,创建两个线程,每个线程负责统计字符串中的一个子串(例如前半部分或后半部分)。最后把统计所得之结果加总起来就是期望的结果。
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <pthread.h>
char input_str[] = "AbaCaZaBBC";
typedef s