C语言线程定义攻略
什么是线程
线程是一种执行路径,是进程中的一个执行流程。一个进程可以拥有多个线程,每个线程都可以独立执行,但是它们都共享相同的资源。
线程的优势
线程可以极大的提高程序的运行效率。当程序的某部分需要长时间运行时,通过创建线程可以使得该部分程序有多个执行流程,让每个线程独立的运行。这样就能提高程序运行效率,减少用户等待时间,提高用户体验。
C语言线程定义
在C语言中,线程的定义需要使用到头文件pthread.h,在该头文件中定义了与线程相关的函数和数据类型:
#include <pthread.h>
pthread_t tid; //线程id
pthread_create(&tid, NULL, function, args); //创建线程
pthread_join(tid, NULL); //等待线程结束
pthread_exit(NULL); //结束线程
pthread_t tid
定义了线程ID,在创建新的线程时会给它赋值pthread_create
是创建一个新线程的函数,它有四个参数:pthread_t *thread
:输出线程的IDconst pthread_attr_t *attr
:线程属性,通常使用默认值NULLvoid *(*start_routine)(void *)
:指向函数的指针,该函数是新线程的起点。该函数可以接收一个参数并返回一个指针。参数的类型为void *,即指向无类型指针的指针。函数返回类型为void *void *arg
:传递给起点函数的参数
pthread_join
是等待线程结束的函数,当线程结束后,它的资源被回收,并且它的返回值可以通过该函数获取pthread_exit
线程结束的函数
示例1:使用多线程计算1~100的和
以下实例演示了如何使用线程来计算1~100的和:
#include <stdio.h>
#include <pthread.h>
long long sum = 0; //需要计算的值
pthread_mutex_t lock;
void *calculate_sum(void *args) {
int i;
long long temp_sum = 0;
for(i = 1; i <= 100; i++) {
temp_sum += i;
}
pthread_mutex_lock(&lock);
sum += temp_sum;
pthread_mutex_unlock(&lock);
pthread_exit(NULL);
}
int main() {
int i;
pthread_t tid[10]; //定义10个线程
pthread_mutex_init(&lock, NULL);
//创建10个计算线程
for(i = 0; i < 10; i++) {
pthread_create(&tid[i], NULL, calculate_sum, NULL);
}
//等待计算线程结束
for(i = 0; i < 10; i++) {
pthread_join(tid[i], NULL);
}
printf("sum = %lld\n", sum);
pthread_mutex_destroy(&lock);
return 0;
}
以上程序中创建了10个线程,每个线程计算1-100的和,最终将结果累加到sum变量中,最终输出结果sum = 5050。
示例2:使用线程读写文件
以下实例演示了如何使用线程来读写文件:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_LINE 1024
pthread_rwlock_t lock; //定义读写锁
void *write_file(void *args) {
FILE *fp = fopen("test.txt", "a+");
if(fp == NULL) {
printf("Open file failed!\n");
pthread_exit(NULL);
}
char *line = "Test line to write!\n";
pthread_rwlock_wrlock(&lock); //加写锁
fputs(line, fp);
pthread_rwlock_unlock(&lock); //解锁
fclose(fp);
pthread_exit(NULL);
}
void *read_file(void *args) {
char buf[MAX_LINE];
FILE *fp = fopen("test.txt", "r");
if(fp == NULL) {
printf("Read file failed!\n");
pthread_exit(NULL);
}
pthread_rwlock_rdlock(&lock); //加读锁
while(fgets(buf, MAX_LINE, fp) != NULL) {
printf("%s", buf);
}
pthread_rwlock_unlock(&lock); //解锁
fclose(fp);
pthread_exit(NULL);
}
int main() {
pthread_t tid[2];
pthread_rwlock_init(&lock, NULL);
pthread_create(&tid[0], NULL, write_file, NULL);
pthread_create(&tid[1], NULL, read_file, NULL);
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_rwlock_destroy(&lock);
return 0;
}
以上程序中,定义了一个读写锁pthread_rwlock_t lock,用于保护对文件的读写。创建了2个线程,一个写文件,一个读文件,两个线程共同操作一个文件test.txt。在写文件时使用写锁,读文件时使用读锁,确保在写文件时不会发生冲突,在读文件时也不会发生冲突。最终读取文件中的所有文本并输出到控制台。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C语言由浅入深讲解线程的定义 - Python技术站