Basic implementation of multi-threading in C language
The basic implementation of multi-threading in C language can be done using the pthread library.
Firstly, the pthread.h header file needs to be included in the program.
#include <pthread.h>
Next, it is necessary to create a thread function to execute the tasks of multi-threading. The definition of the thread function is as follows:
void* thread_function(void* arg) {
// 线程的任务代码
// ...
return NULL;
}
Please note that the return type of a thread function is a void pointer, which can be used to pass the result of the thread.
Next, create and run threads in the main function. Thread creation can be done using the pthread_create function, defined as follows:
int pthread_create(pthread_t* thread, const pthread_attr_t* attr, void* (*start_routine)(void*), void* arg);
“thread is a pointer to the pthread_t type used to store the thread’s ID. attr is a pointer to the pthread_attr_t type used to set the thread’s attributes. start_routine refers to the thread function defined above, with arg being the parameter passed to the thread function.”
Here is an example code for creating and running multiple threads:
#include <stdio.h>
#include <pthread.h>
void* thread_function(void* arg) {
int thread_id = *(int*)arg;
printf("Thread %d is running\n", thread_id);
return NULL;
}
int main() {
pthread_t threads[10];
int thread_ids[10];
for (int i = 0; i < 10; ++i) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, thread_function, &thread_ids[i]);
}
for (int i = 0; i < 10; ++i) {
pthread_join(threads[i], NULL);
}
return 0;
}
In the example above, 10 threads are created and the thread IDs are passed to the thread function through the thread_ids array. Then, the pthread_create function is used to create the threads and the pthread_join function is used to wait for all threads to finish running.
The above is the basic implementation of multithreading in C language. Using the pthread library, it is easy to create and manage multiple threads for concurrent programming.