在现代软件开发中,C语言多线程编程是一项非常重要的技能。通过多线程,我们可以让程序同时执行多个任务,从而提高效率和响应速度。本教程将从零开始,带你掌握pthread(POSIX Threads)这一在Linux/Unix系统中最常用的多线程库,即使是编程小白也能轻松上手。
线程是操作系统能够进行运算调度的最小单位。一个进程可以包含多个线程,这些线程共享进程的内存空间(如全局变量、堆等),但每个线程有自己的栈和寄存器状态。多线程可以让程序“同时”做多件事,比如一边下载文件一边播放音乐。

在Linux或macOS系统中,pthread库通常已经预装。你只需要在编译时链接该库即可:
gcc -o mythread mythread.c -lpthread
注意:-lpthread 是链接pthread库的关键参数。
下面我们编写一个最简单的多线程程序,创建一个新线程并让它打印一条消息。
#include <stdio.h>#include <pthread.h>#include <unistd.h> // 用于sleep函数// 线程执行函数void* thread_function(void* arg) { printf("Hello from the new thread!\n"); sleep(1); // 模拟耗时操作 return NULL;}int main() { pthread_t thread_id; // 创建线程 if (pthread_create(&thread_id, NULL, thread_function, NULL) != 0) { perror("Failed to create thread"); return 1; } printf("Hello from the main thread!\n"); // 等待新线程结束 pthread_join(thread_id, NULL); printf("Thread finished. Main exiting.\n"); return 0;}这段代码展示了C语言并发编程的基本结构:
pthread_create():创建一个新线程。pthread_join():主线程等待子线程完成。void* 类型,并接受一个 void* 参数。线程函数可以通过参数传递数据,也可以返回结果。下面是一个带参数和返回值的例子:
#include <stdio.h>#include <stdlib.h>#include <pthread.h>void* square(void* arg) { int num = *(int*)arg; int* result = malloc(sizeof(int)); *result = num * num; return (void*)result;}int main() { pthread_t tid; int input = 5; int* output; pthread_create(&tid, NULL, square, &input); pthread_join(tid, (void**)&output); printf("Square of %d is %d\n", input, *output); free(output); // 记得释放动态分配的内存 return 0;}当多个线程访问共享资源(如全局变量)时,可能会发生竞态条件(Race Condition)。为了解决这个问题,我们需要使用互斥锁(Mutex)。
#include <stdio.h>#include <pthread.h>int counter = 0;pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;void* increment(void* arg) { for (int i = 0; i < 100000; i++) { pthread_mutex_lock(&mutex); counter++; pthread_mutex_unlock(&mutex); } return NULL;}int main() { pthread_t t1, t2; pthread_create(&t1, NULL, increment, NULL); pthread_create(&t2, NULL, increment, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("Final counter value: %d\n", counter); // 应该是200000 return 0;}如果没有互斥锁,两个线程可能同时读取和写入 counter,导致结果小于200000。
通过本教程,你已经掌握了pthread教程中的核心概念:创建线程、传递参数、等待线程结束以及使用互斥锁进行同步。这些都是多线程入门必备的知识点。
记住,多线程虽然强大,但也容易引入死锁、竞态等复杂问题。建议从小项目开始练习,逐步深入理解并发模型。
继续学习的方向包括:条件变量(pthread_cond_t)、线程池、信号量等高级主题。
希望这篇关于C语言多线程编程的教程对你有所帮助!
本文由主机测评网于2025-12-17发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/2025128901.html