Linux下的C语言多线程编程是指在Linux操作系统中使用C语言编写多线程程序。多线程是指在一个进程中同时运行多个线程,每个线程执行不同的任务,共享进程的资源。多线程编程可以提高程序的执行效率,充分利用多核处理器的性能。
以下是一个简单的C语言多线程示例,使用POSIX线程库(pthread)创建和运行两个线程:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* thread_function(void* arg) {
int* id = (int*)arg;
printf("Thread %d is running\n", *id);
return NULL;
}
int main() {
pthread_t threads[2];
int thread_ids[2] = {1, 2};
for (int i = 0; i < 2; ++i) {
if (pthread_create(&threads[i], NULL, thread_function, &thread_ids[i]) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < 2; ++i) {
pthread_join(threads[i], NULL);
}
return 0;
}
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* thread_function(void* arg) {
pthread_mutex_lock(&mutex);
// 访问共享资源
pthread_mutex_unlock(&mutex);
return NULL;
}
pthread_create
返回非零值,表示线程创建失败。if (pthread_create(&threads[i], NULL, thread_function, &thread_ids[i]) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
通过以上方法,可以有效解决Linux下C语言多线程编程中常见的问题。
领取专属 10元无门槛券
手把手带您无忧上云