C语言并发编程多线程和多进程
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C语言并发编程多线程和多进程C语言并发编程:多线程和多进程
编程中的并发是指程序在同一时间可以执行多个任务或进程。并发编程可以提高程序的效率和性能,使得程序可以同时处理多个任务,实现高度的并行化。在C语言中,实现并发编程的两种常见方式是多线程和多进程。
一、多线程
多线程是指在一个进程中创建多个线程,每个线程可以并行执行不同的任务。C语言提供了pthread库来支持多线程编程。下面简要介绍多线程的一些核心概念和用法:
1. 线程创建与结束
通过pthread_create函数来创建线程,并且使用pthread_join函数等待线程结束。示例代码如下:
```c
#include
#include
void *thread_func(void *arg) {
// 线程执行的代码
return NULL;
}
int main() {
pthread_t tid;
pthread_create(&tid, NULL, thread_func, NULL);
// 其他主线程执行的代码
pthread_join(tid, NULL);
return 0;
}
```
2. 线程同步与互斥
多线程执行过程中,可能会出现共享资源的竞争问题。为了避免竞争,需要使用互斥锁来保护共享资源的访问。示例代码如下: ```c
#include
#include
int counter = 0;
pthread_mutex_t mutex;
void *thread_func(void *arg) {
pthread_mutex_lock(&mutex);
counter++;
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t tid1, tid2;
pthread_mutex_init(&mutex, NULL);
pthread_create(&tid1, NULL, thread_func, NULL);
pthread_create(&tid2, NULL, thread_func, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("Counter value: %d\n", counter);
pthread_mutex_destroy(&mutex);
return 0;
}
```
3. 线程间通信
多个线程之间可以通过共享内存进行通信。C语言提供了一些线
程间共享内存的机制,如全局变量、线程局部存储等。示例代码如下:
#include
#include
int number = 0; // 全局变量
void *thread_func1(void *arg) {
number = 10;
return NULL;
}
void *thread_func2(void *arg) {
printf("Value from thread 1: %d\n", number);
return NULL;
}
int main() {
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, thread_func1, NULL); pthread_create(&tid2, NULL, thread_func2, NULL); pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
```
二、多进程
多进程是指在一个程序中创建多个子进程,每个子进程可以并行执
行不同的任务。C语言提供了fork函数和exec函数来支持多进程编程。下面简要介绍多进程的一些核心概念和用法:
1. 进程创建与结束
通过fork函数来创建子进程,并且通过exit函数来结束进程。示
例代码如下:
```c
#include
#include
#include
#include
#include
int main() {
pid_t pid;
pid = fork();
if (pid < 0) {
printf("Fork error\n");
exit(1);
} else if (pid == 0) {
// 子进程执行的代码
exit(0);
} else {
// 父进程执行的代码
wait(NULL);
printf("Child process finished\n");
}
return 0;
}
```
2. 进程间通信
多个进程之间可以通过管道、共享内存、信号等机制进行通信。C语言提供了一些进程间通信的函数和结构体,如pipe函数、shmget 函数、signal函数等。示例代码如下:
```c
#include