c怎么并行编程

时间:2025-01-24 19:01:22 网络游戏

在C语言中,有多种方法可以实现并行编程,以下是几种常见的方法:

使用pthread库

引入头文件:`include `

创建线程:使用`pthread_create`函数创建线程

示例代码:

```c

include

include

include

void *calculateSum(void *arg) {

int thread_id = *(int *)arg;

int start = thread_id * (ARRAY_SIZE / THREADS_COUNT);

int end = start + (ARRAY_SIZE / THREADS_COUNT);

int sum = 0;

for (int i = start; i < end; i++) {

sum += array[i];

}

return NULL;

}

int main() {

int array[ARRAY_SIZE] = {0};

int sum = 0;

pthread_t threads[THREADS_COUNT];

int thread_ids[THREADS_COUNT];

for (int i = 0; i < THREADS_COUNT; i++) {

pthread_create(&threads[i], NULL, calculateSum, &thread_ids[i]);

}

for (int i = 0; i < THREADS_COUNT; i++) {

pthread_join(threads[i], NULL);

}

for (int i = 0; i < ARRAY_SIZE; i++) {

sum += array[i];

}

printf("Sum: %d\n", sum);

return 0;

}

```

使用C++11的std::thread

示例代码:

```c++

include

include

include

std::mutex mtx;

int shared_data = 0;

void increment() {

std::lock_guard lock(mtx);

shared_data++;

}

int main() {

std::thread t1(increment);

std::thread t2(increment);

t1.join();

t2.join();

std::cout << "Shared data: " << shared_data << std::endl;

return 0;

}

```

使用OpenMP

示例代码:

```c

include

include

int main() {

pragma omp parallel for

for (int i = 0; i < 100; i++) {

printf("Hello from thread %d\n", omp_get_thread_num());

}

return 0;

}

```

使用CUDA

示例代码(简化的CUDA C编程):