C Multithreading: Parallel Processing Guide

In C programming language, you can utilize the pthread library to achieve parallel processing with multiple threads. The specific steps are as follows:

  1. Include the header file: Include the pthread.h header file in the code, which contains declarations for functions and data types related to multi-threading.
  2. Creating threads: Use the pthread_create function to create threads. This function requires parameters such as a pointer to a thread identifier, thread attributes, and a pointer to a function that is to be executed by the newly created thread.
  3. Define a thread function: You need to define a function that will serve as the entry point for the thread, and which will be executed in the newly created thread.
  4. Start thread: After creating a thread using the pthread_create function, use the pthread_join function to wait for the completion of the thread. This function takes the thread identifier as a parameter and waits for the thread specified by the identifier to terminate.

Below is a simple example code demonstrating how to create and start two threads using the pthread library.

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

// 线程函数1
void* thread_func1(void* arg) {
    printf("Thread 1\n");
    pthread_exit(NULL);
}

// 线程函数2
void* thread_func2(void* arg) {
    printf("Thread 2\n");
    pthread_exit(NULL);
}

int main() {
    pthread_t tid1, tid2; // 线程标识符

    // 创建线程1
    pthread_create(&tid1, NULL, thread_func1, NULL);
    // 创建线程2
    pthread_create(&tid2, NULL, thread_func2, NULL);

    // 等待线程1的完成
    pthread_join(tid1, NULL);
    // 等待线程2的完成
    pthread_join(tid2, NULL);

    return 0;
}

In the example above, we created two threads to run functions thread_func1 and thread_func2. Finally, in the main thread, we used the pthread_join function to wait for the completion of both threads. It should be noted that the different threads run in parallel, and their execution order is not guaranteed.

bannerAds