C语言实现多线程:函数调用及实例详解

更新时间:2024-05-01 18:44:18   人气:7508
在C语言中,虽然本身并未直接提供对多线程的内置支持,但通过POSIX(可移植操作系统接口)或Windows API可以实现在C程序中的多线程编程。下面将详细阐述如何使用 POSIX 线程库pthread来创建和管理多个执行流。

首先,在Linux环境下利用pthread.h头文件提供的API,我们可以轻松地在一个进程中启动新的线程:

c

#include <stdio.h>
#include <stdlib.h>
#include<pthread.h>

// 定义每个新线程要运行的任务函数原型
void* thread_function(void *arg);

int main() {
pthread_t tid; // 创建一个线程标识符

if(pthread_create(&tid, NULL, &thread_function, NULL) != 0){
perror("Thread creation failed");
return EXIT_FAILURE;
}

printf("Main Thread: Created another thread.\n");

/* 主线程等待子线程结束 */
if (pthread_join(tid, NULL)) {
fprintf(stderr, "Error joining threads\n");
exit(EXIT_FAILURE);
}

printf("Main thread completed execution after the child thread finished.");

return EXIT_SUCCESS;
}

/* 实现的新线程任务处理函数 */
void* thread_function(void *ignored_arg) {
puts("Newly created thread running...");

sleep(2);

puts("Exiting from new thread.");

return NULL;
}


上述代码展示了以下关键步骤:
1. 首先包含必要的头文件`<pthread.h>`。
2. 在main函数内声明并初始化一个新的pthread_t类型的变量作为线程ID,并通过pthread_create函数创建一个新线程,传入目标为“thread_function”的函数指针以及可能需要传递给该线程的数据参数。
3. 如果成功创建了线程,则主线程继续执行其后续逻辑;否则输出错误消息退出进程。
4. 使用pthread_join让主线程阻塞直到指定的线程完成它的操作,这样确保了两个线程间的同步性。
5. `thread_function()`是被新建线程所执行的实际工作内容,这里只是简单打印一条日志然后休眠两秒后终止。

以上就是基于C语言与POSIX标准下实现多线程的基本流程示例。值得注意的是,实际开发过程中需充分考虑资源竞争、互斥锁等问题以保证并发环境下的数据安全性和正确性。同时对于不同的平台,请相应调整使用的API,例如在Windows上应采用CreateThread等系统调用来构建多线程应用。