在Linux系统中,有多种方法可以利用进程进行并发处理。以下是一些常用的方法:
fork() 和 exec()fork() 系统调用用于创建一个新的进程,而 exec() 系列函数用于在新进程中执行另一个程序。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程
execl("/bin/ls", "ls", "-l", NULL);
perror("execl");
exit(EXIT_FAILURE);
} else {
// 父进程
printf("Child PID: %d\n", pid);
wait(NULL); // 等待子进程结束
}
return 0;
}
pthread 库pthread 库提供了线程编程的接口,可以更轻量级地实现并发。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* thread_function(void* arg) {
int* num = (int*)arg;
printf("Thread %d is running\n", *num);
pthread_exit(NULL);
}
int main() {
pthread_t threads[5];
int thread_args[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
if (pthread_create(&threads[i], NULL, thread_function, &thread_args[i]) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < 5; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
system() 函数system() 函数可以执行一个shell命令,从而实现并发处理。
#include <stdio.h>
#include <stdlib.h>
int main() {
system("ls -l &"); // 在后台执行 ls -l 命令
printf("Main process continues\n");
return 0;
}
async 和 await(C++11及以上)在C++中,可以使用 std::async 和 std::future 来实现异步编程。
#include <iostream>
#include <future>
#include <vector>
int async_task(int n) {
std::this_thread::sleep_for(std::chrono::seconds(1));
return n * n;
}
int main() {
std::vector<std::future<int>> results;
for (int i = 0; i < 5; ++i) {
results.push_back(std::async(std::launch::async, async_task, i));
}
for (auto& result : results) {
std::cout << "Result: " << result.get() << std::endl;
}
return 0;
}
multiprocessing 模块(Python)在Python中,可以使用 multiprocessing 模块来实现并发处理。
import multiprocessing
def worker(num):
print(f"Worker: {num}")
if __name__ == "__main__":
processes = []
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
processes.append(p)
p.start()
for p in processes:
p.join()
joblib 库(Python)joblib 是一个用于并行计算的库,特别适用于CPU密集型任务。
from joblib import Parallel, delayed
def worker(num):
print(f"Worker: {num}")
return num * num
if __name__ == "__main__":
results = Parallel(n_jobs=-1)(delayed(worker)(i) for i in range(5))
print(results)
这些方法各有优缺点,选择哪种方法取决于具体的应用场景和需求。例如,fork() 和 exec() 适用于需要完全独立进程的场景,而 pthread 和 multiprocessing 则更适合需要共享内存或更轻量级线程的场景。