动态库(Dynamic Library):
动态库是一种在程序运行时加载的库文件,与静态库相对。动态库文件通常以 .so
(共享对象)为扩展名。与静态库在编译时链接不同,动态库允许程序在运行时动态地加载和链接库中的代码。
线程(Thread): 线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。
动态库的优势:
线程的优势:
动态库类型:
.so
文件。.dll
为扩展名。线程类型:
应用场景:
动态库加载问题:
/usr/lib
、/usr/local/lib
等标准库路径中,或者设置 LD_LIBRARY_PATH
环境变量指定库文件的路径。线程安全问题:
动态库示例:
假设我们有一个简单的动态库 libmath.so
,提供一个加法函数:
// math.c
int add(int a, int b) {
return a + b;
}
编译生成动态库:
gcc -shared -o libmath.so math.c
线程示例: 以下是一个简单的多线程程序,使用 POSIX 线程(pthread)库:
// thread_example.c
#include <pthread.h>
#include <stdio.h>
void* thread_func(void* arg) {
int* num = (int*)arg;
printf("Thread %d is running
", *num);
return NULL;
}
int main() {
pthread_t thread1, thread2;
int num1 = 1, num2 = 2;
pthread_create(&thread1, NULL, thread_func, &num1);
pthread_create(&thread2, NULL, thread_func, &num2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
编译并运行:
gcc -o thread_example thread_example.c -lpthread
./thread_example
以上示例展示了动态库的创建和使用,以及多线程程序的基本结构。
领取专属 10元无门槛券
手把手带您无忧上云