How to implement multi-threaded parallel computing in the C language?
Implementing parallel computing with multiple threads in C language can be achieved using the pthread library, here is a simple example code:
#include <stdio.h>
#include <pthread.h>
// 定义线程函数
void *thread_function(void *arg) {
int *num = (int *)arg;
int result = 0;
// 计算累加和
for (int i = 1; i <= *num; i++) {
result += i;
}
// 返回计算结果
pthread_exit((void *)result);
}
int main() {
pthread_t threads[2];
int numbers[2] = {100, 200};
int results[2];
// 创建两个线程
for (int i = 0; i < 2; i++) {
pthread_create(&threads[i], NULL, thread_function, &numbers[i]);
}
// 等待线程执行完毕并获取计算结果
for (int i = 0; i < 2; i++) {
pthread_join(threads[i], (void **)&results[i]);
}
// 输出计算结果
for (int i = 0; i < 2; i++) {
printf("Thread %d result: %d\n", i, results[i]);
}
return 0;
}
In this sample code, a thread function called thread_function is first defined. This function takes an integer parameter, calculates the sum from 1 to that parameter, and returns the result as the thread’s return value.
In the main function, two threads are created and different parameters are passed to each thread. The pthread_join function is then used to wait for the threads to finish executing and to obtain the calculation results. Finally, the calculation results are displayed.
It should be noted that multi-threaded parallel computing may involve issues such as race conditions and synchronization problems between threads, which need to be addressed using mechanisms such as mutex. The example code above does not take these issues into account and is only used to demonstrate the basic usage of multi-threading. In practical applications, more complex inter-thread communication and synchronization mechanisms may be required.